Using the Vue.js 3 Composition API, trigger an event when the component is displayed
P粉032900484
P粉032900484 2023-08-28 23:40:07
0
1
583
<p>I have some components in my application that are shown/hidden via buttons and variables, for example v-show="variable", the buttons just set these variables to true/false and I handle these components for a web page, just like browsing a website on different pages. What I want is a way to call a function when the component is displayed on the page. For example, I want to randomly select 2 players to start a game. When the game board is displayed, a message or a warning will pop up only when the player is 2. The important thing is that the event occurred in that instance, and Not before. My idea is to have a function in the script part of the component: </p> <pre class="brush:php;toolbar:false;">function something() { alert("hello"); }</pre> <p>Then find a way to say: </p> <pre class="brush:php;toolbar:false;">When the component is displayed -> if (player == 2) { something(); }</pre> <p>What I'm lacking is how to determine and handle the "when the component is displayed" part. To me the most appropriate logic seems to be to use onMounted, onRendered (I read it only works in a development environment) and onActivated, but they don't seem to work properly/at all. </p>
P粉032900484
P粉032900484

reply all(1)
P粉473363527

I found a way. The problem is: it's combined with onMounted and v-if. I was checking the code to see if I could use v-if instead of v-show, and I remember I deliberately chose to use v-show to handle mine component, but maybe it wouldn't be a problem to change it in this case.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template