fef*_*efe 2 children parent emit vue.js
如何在递归子组件vuejs中发出事件
从vue站点https://vuejs.org/v2/examples/tree-view.html获取树示例
你如何通过点击向父母点击每个点击的元素ID?
如果您不想创建多个Vue实例,这是另一种解决方案.我在单文件递归组件中使用它.
它使用v-on指令(我使用的是@速记).
在您的递归组件中<template>:
<YourComponent @bus="bus"></YourComponent>
Run Code Online (Sandbox Code Playgroud)
在递归组件中methods:
methods: {
bus: function (data) {
this.$emit('bus', data)
}
}
Run Code Online (Sandbox Code Playgroud)
为了开始它,你在孩子中发出一个事件:
this.$emit('bus', {data1: 'somedata', data2: 'somedata'})
该数据将一直向上传输,然后您在调用递归组件的页面中收到该事件:
methods: {
bus (data) {
// do something with the data
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个在Vue.JS树例子中显示它的小提琴.右键单击一个元素,它将在控制台中输出该模型:
https://jsfiddle.net/AlanGrainger/r6kxxoa0/
对于递归元素,您可以在父元素中创建一个事件总线,将其作为 prop 传递给子元素,然后让每个 prop 将其传递给它们生成的任何子元素。
每个子进程都会在总线上发出事件,然后由父进程处理它们。我复制了您链接的树视图练习并添加了总线功能。
// demo data
var data = {
name: 'My Tree',
children: [{
name: 'hello'
},
{
name: 'wat'
},
{
name: 'child folder',
children: [{
name: 'child folder',
children: [{
name: 'hello'
},
{
name: 'wat'
}
]
},
{
name: 'hello'
},
{
name: 'wat'
},
{
name: 'child folder',
children: [{
name: 'hello'
},
{
name: 'wat'
}
]
}
]
}
]
};
var itemId = 0;
// define the item component
Vue.component('item', {
template: '#item-template',
props: {
model: Object,
bus: Object
},
data: function() {
return {
open: false,
id: ++itemId
}
},
computed: {
isFolder: function() {
return this.model.children &&
this.model.children.length
}
},
methods: {
toggle: function() {
if (this.isFolder) {
this.open = !this.open;
this.bus.$emit('toggled', this.id);
}
},
changeType: function() {
if (!this.isFolder) {
Vue.set(this.model, 'children', [])
this.addChild()
this.open = true
}
},
addChild: function() {
this.model.children.push({
name: 'new stuff'
})
}
}
})
// boot up the demo
var demo = new Vue({
el: '#demo',
data: {
treeData: data,
bus: new Vue()
},
created() {
this.bus.$on('toggled', (who) => {
console.log("Toggled", who);
});
}
})Run Code Online (Sandbox Code Playgroud)
body {
font-family: Menlo, Consolas, monospace;
color: #444;
}
.item {
cursor: pointer;
}
.bold {
font-weight: bold;
}
ul {
padding-left: 1em;
line-height: 1.5em;
list-style-type: dot;
}Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<!-- item template -->
<script type="text/x-template" id="item-template">
<li>
<div :class="{bold: isFolder}" @click="toggle" @dblclick="changeType">
{{model.name}}
<span v-if="isFolder">[{{open ? '-' : '+'}}]</span>
</div>
<ul v-show="open" v-if="isFolder">
<item class="item" :bus="bus" v-for="model in model.children" :model="model">
</item>
<li class="add" @click="addChild">+</li>
</ul>
</li>
</script>
<p>(You can double click on an item to turn it into a folder.)</p>
<!-- the demo root element -->
<ul id="demo">
<item class="item" :bus="bus" :model="treeData">
</item>
</ul>Run Code Online (Sandbox Code Playgroud)