英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论