vue常见的三种组件通讯—props,$refs,this.$emit
一.父组件--->子组件 props
1.特点:props是用于父组件向子组件传递数据信息(props是单向绑定的,即只能父组件向子组件传递,不能反向
2.用法:父组件中使用子组件时,绑定要传递的数据,父组件中对要绑定的数据添加方法或者值
子组件通过props接收值
3.示例
// 父组件我是父组件"checkList" /> import addConfiguration from '@/components/addConfiguration.vue' export default { components:{ addConfiguration }, data() { return { checkList: [] } }, methods:{ getList() { .... this.checkList= ... } } }
// 子组件二.子组件--->父组件 $refs 1.特点:父组件获取子组件的方法或者属性,$refs 数据是双向绑定的,子组件可以向父组件传递方法,父组件可以向子组件传递参数 2.用法:父组件通过子组件中 的ref标识来获取子组件的方法或者属性 this.$refs.标识.方法 3.示例:我是子组件我是父组件传递过来的数组{{message}}export default { props: { message: { type: Array, default: () => [] } }, data() { return { } } }
// 父组件我是父组件import addConfiguration from '@/components/addConfiguration.vue' export default { components:{ addConfiguration }, data() { return { } }, methods:{ getList() { this.$ref.transforFntoFather() } } }
// 子组件三.子组件--->父组件 $emit 1.特点:父组件向子组件通信,而通过e m i t 实 现 子 组 件 向 父 组 件 通 信 。 对 于 emit 实现子组件向父组件通信 2.用法: 父组件中的子组件绑定一个事情@事件名 父组件处理事件方法 子组件调用 this.emit(事件名) 3.示例:我是子组件export default { data() { return { } }, methods:{ transforFntoFather() { .... } } }
// 父组件我是父组件import addConfiguration from '@/components/addConfiguration.vue' export default { components:{ addConfiguration }, data() { return { } }, methods:{ initialData() { .... // 请求api接口返回数据 } } }
// 子组件我是子组件export default { data() { return { configCategory:1 } }, mounted(){ this. getListData() } methods:{ getListData() { this.$emit('fatherMethod',this.configCategory) } } }