Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can v-if trigger something? Does v-if raise an event?

Tags:

vue.js

vuejs2

I would like to catch an event and do something when v-if toggles. A conditionally rendered element is rendering. It should be possible to get notified of this, no?

like image 606
bbsimonbb Avatar asked Dec 03 '22 22:12

bbsimonbb


1 Answers

You can setup a watcher on the property that is responsible for the truthy-ness for the conditional rendering (v-if).

html

<div id="app">
    <div v-if="toggleElement">MY ELEMENT</div>
    <button @click="toggleElement = !toggleElement">TOGGLE</button>
</div> 

script

new Vue({
el: '#app',
    data: {
        toggleElement: false
    },
    watch: {
        toggleElement(newValue){
            //do something if toggleElement changes
            alert("Element's v-if toggled");
        }
    }
}) 

Here is the fiddle

like image 87
Vamsi Krishna Avatar answered Mar 14 '23 21:03

Vamsi Krishna