Vue中头痛的组件传值(父传子,子传父,兄弟互传)(简版)
1.html 部分
<!--父组件-->
<div class="parent">
<fieldset>
<legend>我是parent</legend>
我的信息:{{title}} <br>
child1的信息:{{child1mess}} <br>
child2的信息:{{child2mess}} <br>
<child1 :mess='title' @c1top='c1top'></child1>
<child2 :mess='title' @c2top='c2top'></child2>
</fieldset>
</div>
<!-- 子组件1-->
<template id='child1'>
<fieldset>
<legend>我是child1</legend>
我的信息:{{title}} <br>
<!-- 通过自定义事件c1top将数据title当作参数传值给父亲-->
<button @click='$emit("c1top",title)'>给父亲传值</button> <br>
<hr>
<button @click="parmes=mess">接受父亲的值</button> => {{parmes}} <br>
<hr>
<button @click="c2toc1">给child2传值</button> child2的值 => {{child2mess}} <br>
</fieldset>
</template>
<!-- 子组件2-->
<template id='child2'>
<fieldset>
<legend>我是child2</legend>
我的信息:{{title}} <br>
<button @click='$emit("c2top",title)'>给父亲传值</button> <br>
<hr>
<button @click="parmes=mess">接受父亲的值</button> => {{parmes}} <br>
<hr>
<button @click="c1toc2">给child1传值</button> child1的值 => {{child1mess}} <br>
</fieldset>
</template>
2.script部分
let middleVue = new Vue();//使用中间人vue
Vue.component( //组件1
'child1', {
template: '#child1',
props: {
mess: {
type: String,
default: ''
}
},
data() {
return {
title: 'i am child1 message',
parmes: '',
child2mess: '',
}
},
created() { //在组件创建时激活事件并把中间人传过来的值留给自己
middleVue.$on('c2toc1', data => {
this.child2mess = data
})
},
methods:{
c2toc1(){
middleVue.$emit('c1toc2',this.title)
//激活自定义事件 并把自身的数据当作参数传给中间人
}
}
)
Vue.component( //组件2
'child2', {
template: '#child2',
props: {
mess: {
type: String,
default: ''
}
},
data() {
return {
title: 'i am child2 message',
parmes: '',
child1mess: '',
}
},
created() {
middleVue.$on('c1toc2', data => {
this.child1mess = data
})
},
methods:{
c1toc2(){
middleVue.$emit('c2toc1',this.title)
//激活自定义事件 并把自身的数据当作参数传给中间人
}
}
}
)
let vm = new Vue({ //vue主组件
el: '.parent',
data: {
title: 'i am parent message',
child1mess: '',
child2mess: '',
},
methods: {
c1top(data) {
this.child1mess = data //延迟父亲传过来的值的显示 实际上已经传值完毕
},
c2top(data) {
this.child2mess = data
}
}
})