vue非父子通信(兄弟之间通信)
ps:昨天写了父子之间的通信,忘记了可以去看以下小例子哟
要点
兄弟1:通过鼠标点击事件传值:
vm.$emit('事件名',value)
兄弟2:接受值: 注意在mounted()中执行:vm.$on('事件名',callback)
vm是兄弟1和兄弟2的公共部分,可以是main.js,也可以自定义一个,要点代码是:export var bus= new Vue();
直接上代码:
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
export var bus = new Vue();
new Vue({
render: h => h(App),
}).$mount('#app')
兄弟1:Brother1.vue
<template>
<div id="b1">
兄弟1
<span>{ { eleValue}}</span>
<input type="button" @click="elementByValue" value="按钮1">
</div>
</template>
<script>
import { bus} from '../main.js'
export default{
name:'b1',
data(){
return {
eleValue:3
}
},
methods:{
elementByValue:function(){
console.log(this.eleValue)
bus.$emit('val',this.eleValue)
}
}
}
</script>
<style>
</style>
兄弟2:Bother2.vue
<template>
<div id="b2">
兄弟2
<input type="button" @click="getData" value="按钮2">
<span>{ { name}}</span>
</div>
</template>
<script>
import { bus} from '../main.js'
export default {
name: 'b2',
data: function() {
return {
name: 0
}
},
mounted() {
var _this = this;
bus.$on('val', (data) => {
console.log(data);
_this.name = data;
_this.$forceUpdate()
})
},
methods: {
getData: function() {
console.log(this)
this.name++;
}
}
}
</script>
<style>
</style>
注意:
记得在渲染组件中引入哟!!!我的在App.vue中使用。因为我只是做的一个test,项目中没必要把所有的组件都在App.vue中引入。可以放的比如说头部,尾部这样的。看项目怎么要求吧
更多推荐
父子通信、非父子通信
还没有评论,来说两句吧...