Vue-组件之间的数据共享
一、父向子传值
方法: 通过子组件添加自定义属性的方法,来实现父组件向子组件传值的目的。
1.子组件代码
//自定义属性
props: {
init: {
default: 'left',
type: String,
required:true,
}
}
<template>
<div>
{{this.init}
</div>
</template>
2.父组件代码
<template>
<div id="app">
<!--通过子组件的自定义属性传值-->
<Left :init="'myleft'"></Left>
</div>
</template>
二、子向父传值
方法: 在子组件中触发自定义事件,父组件在使用子组件时为其添加自定义事件,自定义事件触发时传递数据。
1.子组件代码
methods: {
add() {
this.count += 1;
//触发自定义事件并且将this.count传递出去
this.$emit('countadd', this.count);
}
}
<template>
<div @click="add">
{{this.count}}
</div>
</template>
2.父组件代码
methods: {
getsoncount(cnt) {
this.count = cnt;
}
}
<template>
<div id="app">
{{this.count}}
//为子组件添加自定义事件
<Left @countadd="getsoncount"></Left>
</div>
</template>
三、兄弟组件传值
方法: 创建 eventBus.js 模块,并向外共享一个Vue 的实例对象,在数据发送方,调用
bus.$emit('事件名称', 要发送的数据)
方法触发自定义事件,在数据接收方,调用bus.$on('事件名称', 事件处理函数)
方法注册一个自定义事件。
1.发送方代码
data() {
return {
//待发送的数据
toright:'szx',
}
},
methods: {
add() {
//触发自定义事件,传递this.toright
eventBus.$emit('lefttoright', this.toright);
}
}
2.eventBus.js代码
//中间介质
//创建eventBus.js 模块,并向外共享一个Vue 的实例对象
//在数据发送方,调用bus.$emit('事件名称', 要发送的数据)方法触发自定义事件
//在数据接收方,调用bus.$on('事件名称', 事件处理函数)方法注册一个自定义事件
import Vue from 'vue';
export default new Vue();
3.接收方代码
data() {
return {
//待接收数据
fromleft:null,
}
},
created() {
//注册自定义事件,等待出发接收数据
eventBus.$on('lefttoright', (str) => {
this.fromleft = str;
})
}