使用场景:兄弟组件之间相互传递数据
先上简单的用法,一个页面上使用
<template>
<view class="content">
<view>
<view @click="sub">{{msg}}</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
msg:"ok"
}
},
onLoad(){
this.$on("event_a",this.bind_a) //将函数绑定到事件
},
methods:{
bind_a(e){
this.msg= "绑定+"+e
},
sub(){
this.$emit("event_a","传入的参数") //触发事件
}
}
}
</script>
兄弟组件传值
//index.vue
<template>
<view class="content">
<view>
<h3>组件A改动组件B</h3>
<br/>
<comp_a></comp_a>
<br/>
<comp_b></comp_b>
</view>
</view>
</template>
<script>
import comp_a from './a.vue'
import comp_b from './b.vue'
export default {
data() {
return {
}
},
onLoad(){
},
components:{
comp_a,
comp_b
},
methods:{
}
}
</script>
//a.vue
<template>
<view>
<view @click="sub">点我</view>
</view>
</template>
<script>
import eventBus from '@/common/eventBus.js'
export default {
data() {
return {
data_a:"aaa"
}
},
methods:{
sub(){
eventBus.$emit('eventa',this.data_a)
}
}
}
</script>
//b.vue
<template>
<view>
{{msg}}
</view>
</template>
<script>
import eventBus from '../../common/eventBus'
export default {
data() {
return {
msg:"bbb"
}
},
mounted(){
eventBus.$on('eventa',(val)=>{
this.msg=val
})
},
}
</script>
//eventBus.js
import Vue from 'vue'
export default new Vue()
网友评论