前言
兄弟组件传值(跨组件传值)–不用vuex管理
vue2写法,vue3已经将bus抽成专门的库了
代码
main.js文件:
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
Vue.prototype.$bus = new Vue()
new Vue({
render: (h) => h(App)
}).$mount('#app')
app.vue文件:
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
<component-a></component-a>
<component-b></component-b>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import ComponentA from './components/componentA.vue'
import ComponentB from './components/componentB.vue'
export default {
name: 'App',
components: {
HelloWorld,
ComponentA,
ComponentB
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件A:
<template>
<div>
<h1>A组件</h1>
<select v-model="selectVal" @change="handleChange">
<option>男生</option>
<option>女生</option>
</select>
</div>
</template>
<script>
export default {
name: 'ComponentA',
data() {
return {
selectVal: ''
}
},
methods: {
handleChange() {
this.$bus.$emit('componentBus', this.selectVal)
}
}
}
</script>
<style></style>
子组件B:
<template>
<div>
<h1>兄弟组件B</h1>
<div>兄弟组件选择的值是:{{ select }}</div>
</div>
</template>
<script>
export default {
name: 'ComponentB',
data() {
return {
msg: '',
select: ''
}
},
created() {
this.$bus.$on('componentBus', (value) => {
this.select = value
})
}
}
</script>
<style></style>
运行效果:
总结
适用兄弟组件传值,且非公共调用的