Home  >  Q&A  >  body text

Using the Vue.js 3 Composition API, trigger an event when the component is displayed

<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粉032900484P粉032900484438 days ago554

reply all(1)I'll reply

  • P粉473363527

    P粉4733635272023-08-29 09:06:51

    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.

    reply
    0
  • Cancelreply