vue 递归组件自定义事件问题

递归组件,事件只执行一次

子组件

<template>

<ul class="tree">

<li>

<span v-html="data.title" @click="nodeClick(data.title)"></span>

<m-tree v-for="(item , idx) in data.children" :data="item" :key="idx"></m-tree>

</li>

</ul>

</template>

<script>

export default {

name: 'mTree',

props: {

data: {

type: Object,

default (){

return {}

}

}

},

methods: {

nodeClick(title){

this.$emit('nodeClick',title);

}

}

}

</script>

父组件

<template>

<div id="app">

<Tree :data="data" @nodeClick="nCllick"></Tree>

</div>

</template>

<script>

import Tree from './components/tree.vue'

export default {

components: {Tree},

name: 'app',

data(){

return {

data: {

'title': '111',

'children': [

{

'title': '111 - 1'

}, {

'title': '111 - 2',

'children': [

{'title': '111 - 2 - 1'}

]

}

]

}

}

},

methods: {

nCllick(title){

console.log(title)

}

}

}

</script>

运行截图

图片描述

我想点击每一行,都打印出当前的内容,可是只执行一次;
看其他ui库的源码,是用了循环到根实例,parent.$emit.call(parent,par);不知道具体解决方法,请大神赐教!

回答:

在组件中调用一下事件

<template>

<ul class="tree">

<li>

<span v-html="data.title" @click="nodeClick(data.title)"></span>

<m-tree v-for="(item , idx) in data.children" :data="item" :key="idx" @nodeClick="outClick"></m-tree>

</li>

</ul>

</template>

<script>

export default {

name: 'mTree',

props: {

data: {

type: Object,

default (){

return {}

}

}

},

methods: {

nodeClick(title){

this.$emit('nodeClick',title);

},

outClick(title){

this.$emit('nodeClick',title);

}

}

}

</script>

回答:

如何调用事件?

回答:

你需要在组件中也注册事件:

Vue.component('mTree', {

name: 'mTree',

props: {

data: {

type: Object,

default (){

return {}

}

}

},

methods: {

nodeClick(title){

console.log('child: ' + title)

this.$emit('nodeClick',title);

},

nCllick(title){

console.log(title)

}

},

template: `

<ul class="tree">

<li>

<span v-html="data.title" @click="nodeClick(data.title)"></span>

<m-tree

v-for="(item , idx) in data.children"

:data="item" :key="idx"

@nodeClick="nCllick"

>

</m-tree>

</li>

</ul>

`

})

new Vue({

el: '#app',

name: 'app',

data(){

return {

data: {

'title': '111',

'children': [

{

'title': '111 - 1'

}, {

'title': '111 - 2',

'children': [

{'title': '111 - 2 - 1'}

]

}

]

}

}

},

methods: {

nCllick(title){

console.log('parent: ' + title)

}

}

})

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">

<m-tree :data="data" @nodeClick="nCllick"></m-tree>

</div>

以上是 vue 递归组件自定义事件问题 的全部内容, 来源链接: utcz.com/a/150137.html

回到顶部