Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJs Tree recursive elements emits to parent

How do you emit event inside recursive child components vuejs

Taking the tree example from vue site https://v2.vuejs.org/v2/examples/tree-view.html

How would you transmit on click to the parent each clicked elements id?

like image 481
fefe Avatar asked Nov 30 '22 22:11

fefe


1 Answers

Here's another solution if you don't want to create multiple Vue instances. I use this in my single file recursive components.

It uses the v-on directive (I'm using the @ shorthand).

In your recursive component <template>:

<YourComponent @bus="bus"></YourComponent>

In the recursive component methods:

methods: {
    bus: function (data) {
        this.$emit('bus', data)
    }
}

To kick it off, you emit an event in a child:

this.$emit('bus', {data1: 'somedata', data2: 'somedata'})

That data will be transmitted all the way up the chain, and then you receive that event in the page that called your recursive component:

methods: {
    bus (data) {
        // do something with the data
    }
}

Here's a fiddle showing it in action on the Vue.JS tree example. Right-click on an element, and it will output that model in the console:

https://jsfiddle.net/AlanGrainger/r6kxxoa0/

like image 142
Alan Grainger Avatar answered Dec 04 '22 07:12

Alan Grainger