父子组件之间传值(props/$emit):
父组件:
<childerComponent :fatherVal="fatherVal" @backValFather="backValFather"></childerComponent> data(){
fatherVal:'我是父组件的值'
},
methods:{
backValFather(val){
console.log(val); //'我是子组件传给父组件的值'
}
}
子组件:
<div @click="triggerClick"></div>
props:['fatherVal'],
created:{
console.log(this.fatherVal); //'我是父组件的值'
},
methods:{
triggerClick(){
this.$emit('backValFather','我是子组件传给父组件的值')
}
}
父子组件之间获取值或方法(ref/parent)
父组件获取子组件:
<childerComponent ref="childerComponentRef"></childerComponent>
this.$refs.childerComponentRef.val //val 子组件data的数据或方法名( 方法需加() )
子组件获取父组件:
this.$parent.parentVal
非父子组件之间传值(在这里我介绍我常用的eventBus方式)
1、新建公共文件(如:EventBus.js) ,并引入 EventBus.js文件中:
import Vue from 'vue'; export default new Vue;
需要传递消息的两个组件中引入
import EventBus from '@/components/utils/EventBus.js';
2、发送消息的文件中
EventBus.$emit('msgEvent','发送的值')
3、接收消息的文件中
//注意 ventBus.on('msgEvent',(e) => { //e 接收到的值 })`