Vue组件间的通信
我们知道Vue开发是组件化的开发,那么组件化开发就绕不过组件间的通信这一点,以往在vue项目的开发之中
用vuex进行数据的集中处理,但这是对于大的项目来说,如果只是一个小的项目使用vuex就划不来了。所以这个时候
就需要组件间的通信了。
组件间的通信主要有三个类别:
1.父子组件的通信
2.子与父组件的通信
3.兄弟组件的通信
父子组件的通信
父组件传递数据给子组件需要强制绑定一个属性给子组件的映射标签上,然后子组件可以通过props获得父组件传递过来的数据。
Parent.vue
<template>
<div>
<h1>Parent</h1>
<child :name="childName" />
<button @click="changeChildName">change the child name</button>
</div>
</template>
<script>
import Child from './Child';
export default {
components: {
Child,
},
data() {
return {
childName: 'child name is what?',
};
},
methods: {
changeChildName() {
this.childName = 'no name';
},
},
};
</script>
Child.vue
<template>
<div>{{name}}</div>
</template>
<script>
export default {
props: ['name'],
};
</script>
子组件传递数据给父组件
子组件触发事件,父组件监听事件做出数据改变。总结来说就是:父组件绑定自定义事件,子组件触发父组件的自定义事件并向其传递参数。
parent.vue
<template> <div id="app"> <p>请输入单价: <input type="text" v-model="price"></p> <page1 :price="price" @downPrice="downPrice"></page1> <page2></page2> </div> </template> <script> export default { name: "App", data() { return { price: "" }; }, components: { Page1, Page2 }, methods: { downPrice(count) { this.price = (this.price - count).toString(); } } }; </script>
children.vue
<template>
<div>
<p><span>单价:</span><span>{{price}}</span> <button @click="downPrice(this.count)">降价1元</button></p>
<p>数量: {{count}} </p>
</div>
</template>
<script>
export default {
props:{
price:{
type:String,
default:''
}
},
data(){
return{
count:10
}
},
methods:{
downPrice(count){
this.$emit('downPrice',count)
}
}
}
</script>
兄弟组件间的通信
这个时候需要我们定义一个空的Vue实例
bus.js
import Vue from 'vue' export default new Vue()
a.vue
<template> <div class='a'></div> </template> <script> import Bus from 'bus.js' ; export default { name: "a", created() { // 在需要的传递数据的时候调用sendData方法,这里模拟调用 this.sendData(); }, methods: { sendData () { Bus.$emit('listenToA', 'hello'); } } } </script>
b.vue
<template> <div class='b'></div> </template> <script> import Bus from 'bus.js'; export default { name: "b", mounted() { Bus.$on('listenToA', this.getAData); }, methods: { getAData (val) { console.log(`a组件传递过来的数据: ${val}`); // hello } } } </script>
通过$emit将事件和参数传递给b.vue
通过$on接收接收参数和相应事件

浙公网安备 33010602011771号