父子组件传递数据
子组件给父组件传递数据,通过事件机制
子组件给父组件发送一个事件"this.$emit()",携带上数据this.$emit(“事件名”, 携带的数据…) 携带的数据可以多个
父组件通过接收 “事件名” 获取子组件传递给父组件的数据
子组件
<!-- 组件 -->
<template>
<el-tree @node-click="nodeClick" :data="menus" :props="defaultProps" node-key="catId" ref="menuTree">
</el-tree>
</template>
<script>
export default {
data() {
//这里存放数据
return {
menus: [],
expanded: [],
defaultProps: {
children: "children",
label: "name",
},
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
/**
* @description: node-click 节点被点击时的回调
* @param {*} data 该节点所对应的对象
* @param {*} node 节点对应的 Node
* @param {*} component 节点组件本身
* @return {*}
*/
nodeClick(data, node, component) {
console.log('子组件触发 node-click 事件', data,node,component);
/**
* 向父组件发送事件
* "nodelistenEvent"--定义的事件名
* data, node, component--传递给父组件的数据,在父组件中监听 nodelistenEvent
*/
this.$emit("tree-node-click", data, node, component)
}
},
}
</script>
父组件
<template>
<el-row :gutter="20">
<el-col :span="6"> <category @tree-node-click="treeNodeClick"></category></el-col>
</el-row>
</template>
<script>
export default {
data() {
//这里存放数据
return {
menus: [],
expanded: [],
defaultProps: {
children: "children",
label: "name",
},
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
/**
* @description: 监听子组件传入的数据
* @param {*} data 子组件传入数据对象
* @param {*} node 子组件传入节点对应的 Node
* @param {*} component 子组件节点组件本身
* @return {*}
*/
treeNodeClick(data, node, component){
console.log('父组件感知子组件被点击', data, node, component);
},
},
}
</script>
@tree-node-click=“treeNodeClick”:监听子组件传递的事件并用 treeNodeClick 方法接收
结果