采用bus 第三方总线的方式传值
第一步
是封装总线bus.js
import Vue from 'vue'
export default new Vue()
第二步
是编写组件a
<template>
<div>
<el-button type="primary" @click="getChange">消息</el-button>
</div>
</template>
<script>
import bus from './bus'
export default {
data(){
return{
msg:1
}
},
methods:{
getChange(){
bus.$emit("hahavalue",this.msg+1);
}
}
}
</script>
<style scoped>
</style>
第三步
是编写组件b
<template>
<div>
<el-button type="primary" @click="getValue">新闻{{valuec}}</el-button>
</div>
</template>
<script>
import bus from './bus'
export default {
data(){
return{
valuec: ''
}
},
getValue(){
bus.$on("hahavalue",msg=>{
this.valuec= msg;
console.log('tag', this.valuec)
})
},
mounted(){
bus.$on("hahavalue",msg=>{
this.valuec= msg;
console.log('tag', this.valuec)
})
}
}
</script>
<style scoped>
</style>
第四步
是编写二者的父组件
<template>
<div>
<Message/>
<News/>
</div>
</template>
<script>
import Message from './Message'
import News from './News'
export default {
components:{
Message ,
News
}
}
</script>
<style scoped>
</style>
到这里就可以运行测试了
总结: 编程路漫漫,坚持是关键