在项目研发中,组件之间最常见的关系分为两种:
1.父子关系
2.兄弟关系
一父子关系
父--->子数据共享使用自定义属性
父--->子共享数据
父组件为:
//父组件 <template> <div class="root"> <h1>app根组件</h1> <hr> <Left :msg="message" :user="userinfo"></Left> </div> </template> <script> import Left from './components/left.vue' export default { data(){ return{ message:'hello', userinfo:{name:'www',age:18}, } }, components:{ Left } } </script>
子组件为:
//子组件 <template> <div class="left-containt"> <h3>left组件</h3> <p>{{ msg }}</p> <p>{{ user }}</p> </div> </template> <script> export default { props:['msg','user'] } </script> <style scoped> .left-containt{ background-color: pink; height:200px } </style>
子--->父共享数据
子组件向父组件共享数据使用自定义事件
父组件:
//父组件 <template> <div class="root"> <h1>app根组件------{{ countFromSon }}</h1> <p>{{ userinfo }}</p> <p>{{ message }}</p> <hr> <Right @numchange="getNumCount"></Right> <Left :msg="message" :user="userinfo"></Left> </div> </template> <script> import Left from './components/left.vue' import Right from './components/right.vue' export default { data(){ return{ message:'hello', userinfo:{name:'www',age:18}, countFromSon:0 } }, methods:{ getNumCount(val){//val的值是通过this.$emit('numchange',this.count) //中的第二个参数传过来的 this.countFromSon=val } }, components:{ Left, Right } } </script> <style> </style>
子组件:
//子组件 <template> <div class="right-containt"> <h3>right组件----{{ count }}</h3> <button @click="add">+1</button> </div> </template> <script> export default { data(){ return{ count:1 } }, methods:{ add(){ this.count++; this.$emit('numchange',this.count) } } } </script> <style> .right-containt{ background-color: purple; height:200px } </style>
二兄弟关系
兄弟组件之间数据共享的方案是EventBus
1创建eventBus.js模块,并向外共享一个Vue的实例对象。
2在数据发送方,调用bus.$emit('事件名称’,要发送的数据)方法触发自定义事件
3在数据接受方,调用bus.$on('事件名称’,事件处理函数)方法注册自定义事件
数据发送方:
//数据发送方
import bus from './eventBus.js'
export default{
data(){
return{
msg:"hello"
}
},
methods:{
send(){
bus.$emit("share",this.msg)}
}
}
数据接收方:
//数据接收方
import bus from './eventBus.js'
export default{
data(){
return{
msgFromLeft:""
}
},
created:{
bus.$on("share",val=>this.msgFromLeft=val)}
}
eventBus.js
import Vue from 'vue'
export default new Vue()