vue组件之间通信方式有三种: 父传子、子传父、兄弟组件相互传值
1.父组件向子组件传值(通过props)
- 在父组件中通过import引入子组件并组册
- 在子组件标签身上添加自定义属性将要传递的值绑定到自定义属性上
- 一定要加v-bind(简写:)否则会将字符串传过去
父组件
<template>
<div id="app">
<HelloWorld :userMsg="userInfo"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import Right from './components/Right.vue'
export default {
name: 'App',
data() {
return {
msg: '父组件里面的值',
}
},
components: { HelloWorld }
}
</script>
子组件
<template>
<div>
<h1>{{ AppMsg }}</h1>
</div>
</template>
通过props接收父组件传过来的值
<script>
export default {
name: 'HelloWorld',
props: ['AppMsg']
}
</script>
2.子组件向父组件传值(通过自定义事件)
- 使用$emit
- 通过自定义事件方法接收
子组件
<template>
<div>
<h1>子组件向父组件传输数据</h1>
<button @click="onShow">点我传值</button>
</div>
</template>
<script>
export default {
name: 'Right',
data() {
return {
info: '我是子组件里面的数据'
}
},
methods: {
onShow() {
this.$emit('receive', this.info)
}
}
}
</script>
父组件
<template>
<div id="app">
<Right @receive="getInfo"></Right>
</div>
</template>
<script>
import Right from './components/Right.vue'
export default {
name: 'App',
data() {
return {
msg: '',
}
},
methods: {
getInfo(val) {
this.msg = val
}
},
components: { Right }
}
</script>
3.兄弟组件之间的传值(通过eventBus)
- 新建eventBus.js文件
- 导入vue实例
- 在兄弟组件导入evenBus.js
- 发送数据使用bus.$emit()
- 接收数据使用bus.$on()
- 通过ceated()监听自定义事件
eventBus.js
import Vue from 'vue'
export default new Vue()
兄弟组件A(发数据)
<template>
<div>
<button @click="send">点我给兄弟组件传值</button>
</div>
</template>
<script>
import bus from '../eventBus'
export default {
name: 'Right',
data() {
return {
str: '是兄弟就来砍我'
}
},
methods: {
send() {
bus.$emit('share', this.str)
}
}
}
</script>
兄弟组件B(接收数据)
<template>
<div>
<h1>{{ msgAtBrothers }}</h1>
</div>
</template>
<script>
import bus from '../eventBus'
export default {
name: 'HelloWorld',
data() {
return {
msgAtBrothers: ''
}
},
created() {
bus.$on('share', (res) => {
this. msgAtBrothers = res
})
},
}
</script>