在 vue-cli 构建的项目中实现父子组件通信
核心点
1.设置组件的 ref 属性
2.父组件给子组件传值 , 使用 :valueName , 子组件 使用 props:[‘valueName’] 接收 {{valueName}} 直接使用
3.子组件调用父组件的方法 需要在组件上 添加 @methedName="(需要调用的方法名)" 子组件使用 this.emit(“methedName”)调用
4.父组件调用子组件 data 内定义的属性及方法 使用 this.$refs.(定义的 ref 名).(valueName/methodName)
父组件
<template>
<dropList ref="dropList"
:dropdata=“data”
@test=“testMethod”
:tid=“1” >
</dropList>
<template>
<script>
import dropList from "../components/index/dropList"
export default {
components: {
dropList
},
methods : {
// 供子组件调用的方法
testMethod(){
console.log("testMethod trigger ...")
},
// 父组件想要 访问或设置子组件data定义的的变量
// 给 组件 设置 ref 的值
changeOrgetChildData(){
//获取子组件的变量
this.$refs.dropList.dataName
//设置子组件内的变量
this.$refs.dropList.dataName=xxx
},
triggerChildMethod(){
//调用子组件内的方法
this.$refs.dropList.methodName();
}
}
}
</script>
子组件
<template>
<div>
<!-- 调用父组件传给子组件的变量 -->
{{dropdata}}
</div>
<template>
<script>
export default {
props : ['dropdata'] ,//接收父组件传给子组件的变量
data : {
return {
dataName : " "
}
}
methods : {
//子组件内 调用父组件 testMethod 方法
triggetParentMethod(){
this.$emit("test")
}
}
}
</script>