vue 组件间传值
1.父组件向子组件进行传值
2.子组件向父组件传值
3.相邻兄弟组件间进行传值
4.远兄弟组件传值
5.EventBus传参
一、父传子
原理: 父组件控制子组件,通过 prop 自定义标签属性
结果:
二、子传父
子传父通过自定义事件,使用 $emit() 发送
// 父组件
<template>
<div>
<h1>father</h1>
{{ count }}
<child @increaseBy="increaseCount"/>
<!-- 2. 在父组件设置 监听 -->
</div>
</template>
<script>
import child from '../components/DateSon.vue'
export default {
components :{ child },
data(){
return {
count: 0
}
},
methods:{
increaseCount(n){
this.count = this.count + n;
}
}
}
</script>
// 子组件
<template>
<div>
<!-- 1. 在子组件中通过 $emit() 来触发事件 -->
<!-- this.$emit('自定义事件名称','发送的事件参数') -->
<button @click="$emit('increaseBy', 1)">发送</button>
</div>
</template>
<script>
methods: {
submit(){
this.emit('submit')
}
}
</script>
三、兄弟间传值
1. bus 总线
2. 子A 传 父 ,父传子 B
3. vuex
1. bus 总线
(1)在assets 文件夹中创建一个 eventBus.js 的文件,创建一个 bus 总线
// eventBus.js
// bus 总线传值
import Vue from 'Vue';
export default new Vue;
(2)创建一个父组件 father.vue 引入两个子组件(方便查看变化)
<template>
<div>
<childA></childA>
<childB></childB>
</div>
</template>
<script>
import childA from '../components/childA';
import childA from '../components/childA';
export default {
components:{childA, childB},
}
</script>
(3)创建 childA.vue
<template>
<div>
<h1>childA</h1>
<h2>B: {{message}}</h2>
<button @click="twoHandle">
A 控制 ++
</button>
</div>
</template>
<script>
import bus from '../assets/eventBus';
export default{
name: 'one',
data(){
return {
message: 100,
num: 100
}
},
methods:{
twoHandle(){
this.num++;
// 通过bus 总线传递信息 事件名 需要传递的值
bus.$emit('sendBybus', this.num);
}
},
// 使用 Vue 生命周期函数 mounted
// 在 mounted 期间,数据绑定已经完成,将真实 DOM 挂载到页面
// 在此期间值获取过来
mounted(){
// 通过调用 $on() 监听事件
bus.$on('sendBy', data => {
this.message = data;
})
}
}
</script>
(4)创建 childB.vue
<template>
<div class="two">
<h1>childB</h1>
<h2>A: {{num}}</h2>
<button @click="sendToMessage">
B 控制--
</button>
</div>
</template>
<script>
import bus from '../assets/eventBus';
export default {
name: 'two',
data(){
return {
message: 100,
num: 100
}
},
methods:{
sendToMessage(){
this.message--;
bus.$emit('sendBy', this.message);
}
},
mounted(){
bus.$on('sendBy', data => {
this.num = data;
})
}
}
</script>
2. 子A 传 父 ,父传子 B
(1)创建 father.vue 组件
// father.vue
<template>
<div>
// 子传父 使用自定义事件,通过 $emit() 发送
<sonA @sendSonB="getData"></sonA>
// 父传子 子组件使用:props 父组件使用 :绑定
<sonB :message="msg"></sonB>
</div>
</template>
<script>
import sonA from '../son1.vue'
import sonB from '../son2.vue'
export default {
name: 'father',
components:{sonA, sonB},
data(){
return{
msg: ''
}
},
methods:{
getData(msg){
this.msg = msg;
}
}
}
</script>
(2)创建 son1.vue 组件
<!-- 子传父 -->
<template>
<div>
<button @click="$emit('sendSonB', '我是sonA发的')">
发送
</button>
</div>
</template>
<script>
export default {
name: 'son1',
}
</script>
(3)创建 son2.vue 组件
<!-- 父传子 -->
<template>
<div>
<h1>sonB: {{message}}</h1>
</div>
</template>
<script>
export default {
name: 'son2',
props: ['message']
}
</script>
3. vuex