一、父传子
子组件中定义一个props,用来取出父组件传来的值
<script>
export default {
props:['msg'] //子组件定义props
}
</script>
在父组件中对子组件的自定义属性绑定父组件的变量
<template>
<div class="parent">
//子组件,绑定data中需要传送的值
<Children :msg="message"></Children>
</div>
</template>
<script>
import Children from '../components/Children'
export default {
name: 'Parent',
components: {
Children
},
data() {
return {
message:'hello world'
}
},
}
</script>
二、子传父
使用自定义事件,在父组件中给子组件绑定一个处理函数
<template>
<div class="parent">
<Children @numChange = 'getNewNum'></Children>
</div>
</template>
<script>
import Children from '../components/Children'
export default {
data(){
return {numFromSon:0}
},
methods:{
getNewNum(val){
this.countFromSon = val
}
}
</script>
子组件中使用$emit出发父组件中的函数进行传参
export default {
data(){
return {num 0}
},
methods:{
count(){
this.count +=1
this.$emit('numChange',this.count)
}
}
}
三、兄弟组件间传值
采用事件总线eventBus,可以理解为在组件之间建立一个中转站
1.创建一个新的eventBus实例
import Vue from 'vue'
const eventBus = new Vue() //创建Vue实例:eventBus
exoprt default eventBus //暴露
2.在各组件中引入eventBus
import eventBus form '../eventBus.js'
3.使用$emit传参
eventBus.$emit('sendMsg','Hello World')
4.使用$on接受参数
eventBus.$on('sendMeg',(msg)=>{
console.log(msg)
}
)
总结:多练