现象:
自定义树形组件时,使用 $parent 和 $emit 方法子组件都调用不到父组件。
原因:
树形控件使用了组件递归的思想,所以只要递归了一层之后就不是严格的父子关系了,所以 $emit 方法是不合适的。
$emit使用的一些条件:
1.组件之间是严格的父子关系。
2.自定义的事件名必须全为小写。
因为是树形结构,所以它的层数是不确定,所以 $parent方法也是不合适的。
解决方法:使用 $listeners 和 $attrs 实现通信。
“祖辈”组件(父组件):
<div class="tree-scroll">
<child
:label="title"
:treeData="children"
@childMethod="childMethod" />
</div>
子组件:
<template>
<div>
// 递归
<child
:key="children.key"
v-for="children in treeData"
:treeData="children.children"
:label="children.title"
v-bind="$attrs" // 绑定$attrs属性,孙组件可以获取到祖辈组件中传递下来的属性
v-on="$listeners" // 使孙组件也可以调用祖辈组件的方法
>
</child>
</div>
</template>
<script>
export default {
name: 'child',
data () {
}
},
props: {
treeData: {
type: Array,
default: () => []
},
label: {
type: String,
default: () => ''
}
},
methods: {
calFatherMethod (e) {
// 调用祖辈组件函数
this.$listeners.childMethod()
}
}
}
</script>