父组件传值子组件 兄弟组件传值
子组件:
emitToFather() {
this.$emit("child_Mess", this.childMess)
this.$emit("update:childMessc", this.childMessc)
}
父组件两种接收:
@child_Mess="getChildVal" 调用方法:getChildVal(mess){console.log(mess)}
:childMessc.sync="childMessc" 赋值变量:mounted(){console.log(this.childMess)}
1.在main.js创建挂载原型
Vue.prototype.eventBus= new Vue({ router, render: h => h(App) }).$mount('#app')
组件1发起
methods:{ testBus() { this.$router.push('simpleTwo') // this.eventBus.$emit('simpleOne', '点击了simpleTwo按钮') } }, beforeDestroy() { this.eventBus.$emit('simpleOne', '点击了simpleTwo按钮') }
组件2监听
created() { this.eventBus.$on('simpleOne' ,val=>{console.log(val)}) }, destroyed() { this.eventBus.$off('simpleOne') },
注意要销毁
2.新建bus.js
import Vue from 'vue' // 初始化一个新的vue实例,作为中央总线,然后组件引用时调用这个bus.js const eventBus = new Vue() export default eventBus
在组件中
import bus from bus.js mounted() { bus.$emit('bujs',this.name) }
import bus from bus.js created() { bus.$on('bujs',(val) =>{ consile.log(val) }) }