Vue.js 3 Composition API在组件显示时触发事件

huangapple go评论65阅读模式
英文:

Vue.js 3 Composition API trigger an event when a Component is shown

问题

I have some components in my app that I show/hide through buttons, through variables, like v-show="variable" and the buttons just set those variables true/false, I'm handling those components as webpages, like you browse through a website on different pages. What I'm looking for is a way to call a function only when a component is shown on the page. Like, I have to randomize 2 players to start a match and when the board for the game gets shown, only if the player is 2, a message appears or an alert appears or whatever, the important is the event occurs in that instance, not before. My idea would be to have a function like

function something() { alert("hello"); }

in the script section of the component and then find a way to say

when the component gets shown -> if (player == 2) { something(); }

What I lack is how to determine and handle the "when the component gets shown" part. The most logic to use it seems to me would be onMounted, onRendered (which I read does work only while in dev) and onActivated, but they don't seem to work properly/at all.

英文:

I have some components in my app that I show/hide through buttons, through variables, like v-show="variable" and the buttons just set those variables true/false, I'm handling those components as webpages, like you browse through a website on different pages. What I'm looking for is a way to call a function only when a component is shown on the page. Like, I have to randomize 2 players to start a match and when the board for the game gets shown, only if the player is 2, a message appears or an alert appears or whatever, the important is the event occurs in that instance, not before. My idea would be to have a function like

function something() { alert("hello"); }

in the script section of the component and then find a way to say

when the component gets shown -> if (player == 2) { something(); }

What I lack is how to determine and handle the "when the component gets shown" part. The most logic to use it seems to me would be onMounted, onRendered (which I read does work only while in dev) and onActivated, but they don't seem to work properly/at all.

答案1

得分: 1

我找到了一种方法。问题是:它与onMounted结合使用v-if时有效。我现在正在检查代码,看看是否可以使用v-if代替v-show。我记得我有意选择使用v-show来处理我的组件,但也许在这种情况下改变一下不会有问题。

英文:

I found a way. The problem is: it works with onMounted combined with v-if. I'm checking now the code to see if I can use v-if instead of v-show, I remember I knowingly chose to use v-show to handle my components but maybe in this case it won't hurt to make the change.

huangapple
  • 本文由 发表于 2023年4月11日 00:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定