父子传值:
1、父传子:子组件通过props方法接受数据
2、子传父:
子组件写法:
<button @click="toParent('我要去父组件')">向父组件传值</button>
toParent(val) { this.$emit('parentFn',val) }
父组件接收:
定义子组件的方法<child @parentFn="change($event)"></child>
change(data) { console.log(data) }
非父子传值
1、通过eventBus(即通过on监听、emit触发的方式)
// 定义一个新的vue实例专门用于传递数据,并导出,存放在common方法下 import Vue from 'vue' export default new Vue()
// 在所需组件中引入
import bus from '上述文件的路径'
传值组件用bus.$emit('自定义方法名',值)
接收用bus.$on('自定义方法名', (值) => {
console.log(值)
// todo 处理
})