changeText: function () {
this.text = '我是经过改动的一行文本'
}
},
components: {
eldestSon: eldestSon,
youngestSon: youngestSon
}
}
</script>
<style>
#father div{
border: 1px solid grey;
padding: 10px;
margin: 10px;
}
</style>
兄弟组件1:
<template>
<div>
<p>我是兄弟组件:eldestSon</p>
<p>我有一个可变数据text:{{ text }}</p>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
default: ''
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>兄弟组件2:
<template>
<div>
<p>我是兄弟组件:youngestSon</p>
<button @click="changeText">更改eldestSon兄弟组件中的文本</button>
</div>
</template>
<script>
export default {
props: {
changeText: {
type: Function,
default: () => {}
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>点击前:

点击后:

图解:

如果两个兄弟组件间存在这种数据关系的话,我们可以尝试寻找其共同的父组件,使数据和相关方法“提升”到父组件内部,并向下传给两个子组件
这样,其中一个子组件取得了数据,另外一个子组件取得了改变数据的方法,便可以实现上述的数据沟通
【注意】这种场景存在局限性,它要求两个组件有共同父组件。对于这种场景之外的处理方法,请看下文
全局组件间的数据交流——Vuex
我上述的许多场景里面,都运用到了props或者函数传参的方式去处理组件间的数据沟通。然而在稍大型的应用里面,它们都不约而同地给我们带来了很大的麻烦
例如:
1.通过props从父组件向子组件传递数据










