1、组件间的传值
![](https://img.haomeiwen.com/i13133049/b07b4f4e4bc376b3.png)
1.1 父组件向子组件传值
子组件自定义一个属性
![](https://img.haomeiwen.com/i13133049/346da0722abcb990.png)
父组件通过自定义属性绑定值
![](https://img.haomeiwen.com/i13133049/d45374b3b15c7c14.png)
子组件调用自定义属性来拿到值
![](https://img.haomeiwen.com/i13133049/d9b12142f7d90ca4.png)
1.1 完)
1.2 子组件向父组件传值
子组件自定义一个事件
![](https://img.haomeiwen.com/i13133049/0b6d5977a73cad84.png)
父组件通过自定义事件绑定一个方法来接收值
![](https://img.haomeiwen.com/i13133049/fb9a871452f723d6.png)
![](https://img.haomeiwen.com/i13133049/f7cbf7ebe18e8d6d.png)
![](https://img.haomeiwen.com/i13133049/1a42211cb2f59e9b.png)
1.3 兄弟组件间传值
新建一个js文件作为兄弟组件间传值的中转站(new 一个vue)
![](https://img.haomeiwen.com/i13133049/90e07393f4240842.png)
组件1把值先传到bus
![](https://img.haomeiwen.com/i13133049/80c9ef508e7e6b33.png)
组件2从bus接收值
![](https://img.haomeiwen.com/i13133049/8fc42c075f3c2552.png)
![](https://img.haomeiwen.com/i13133049/6e16ecb45f54a8a0.png)
【完整代码】
parent.vue(父组件)
import Children1 from './children1'
import Children2 from './children2'
export default {
name: "parent",
components:{
Children1,
Children2
},
data(){
return {
toChildren:'',
getChildren:''
}
},
methods:{
getChildrenData(data){
this.getChildren = data;
}
}
} body{
background: #eee;
}
.container{
width: 100%;
}
.header{
width: 100%;
}
.main{
width: 985px;
margin: 50px auto;
}
.children1,.children2{
width: 40%;
height: 300px;
margin: 0 20px;
display: inline-block;
background: #909399;
color: #fff;
}
.getData{
color: darkred;
height: 50px;
}
children1.vue 子组件1
import bus from '../eventBus/bus'
export default {
name: "children",
props:['getData'], //子组件自定义一个属性
data(){
return {
toBrother:''
}
},
methods:{
dataToBrother(){
bus.$emit('toBrother',this.toBrother)
}
}
} h1{
height: 50px;
color: darkred;
}
children2.vue 子组件2
import bus from '../eventBus/bus'
export default {
name: "children2",
data(){
return {
toParentData:'',
dataFromBrother:''
}
},
created(){
bus.$on('toBrother',(data)=>{
this.dataFromBrother = data;
})
},
methods:{
dataToParent(){
this.$emit('toParent',this.toParentData)
}
}
} h1{
height: 50px;
color: darkred;
}
bus.js
import Vue from 'vue'
export default new Vue
网友评论