Vue.js - What is the self modifier Vue.js - What is the self modifier vue.js vue.js

Vue.js - What is the self modifier


If a parent node and child node are registered with same type of event then when that type event dispatches then handlers of parent and child are called.

Here is an example fiddle.

Try removing self from click event modifier of the parent div then click on the child div.

  1. First the child handler is called.
  2. Parent handler is called.

    <div class="parent" v-on:click="log('from parent')">  Parent  <div class="child" v-on:click="log('from child')">    Child  </div></div>

If you put back self modifier and clicking on the child div doesn't call the parent handler.


Let's i explain difference.

<div id="app">    <div class="root" v-on:click="log('root')">root        <div class="parent" v-on:click.self="log('parent')">Parent            <div class="child" v-on:click="log('child')">Child            </div>        </div>    </div></div>

Do you know about event phases?

Capture (event.eventPhase = 1)Target (event.eventPhase = 2)Bubbling (event.eventPhase = 3)

By default if you add event listener for element it will work in bubbling mode.

If you click on child in example, you will get output:

childroot

Modificator self say: 'If user click on me (my area or borders), please trigger handler'

If you remove self:

<div class="parent" v-on:click="log('parent')">

and click on child, you will get output:

childparentroot 

If you add stop:

<div class="parent" v-on:click.stop="log('parent')">

and click on child, you will get output:

childparent

You will not get root, because stop cancel event bubbling (event.stopPropagation).

If you will use self it doesn't stop bubbling!


As the docs says:

only trigger handler if event.target is the element itself

i.e. not from a child element

So if you want to capture an event, which is not being triggered from anywhere in child component, but when clicking on the whole component, you can use this modifier.