一、父传子
父组件:<son :msg=“fatherMsg”></son>
子组件:props:[‘msg’]
//父组件
<template>
<div>
<son :msg="fatherMsg"></son>
</div>
</template>
<script>
import son from './son'
export default {
data(){
return {
fatherMsg:'父组件的msg',
}
},
components:{
son
}
}
</script>
//子组件
<template>
<div>
子组件收到的消息:{{msg}}
</div>
</template>
<script>
export default {
props:['msg'],
}
</script>
二、子传父
父组件:
<son @自定义事件名称=“方法”></son>
子组件:
props:[‘自定义事件名称’]
this.$emit(自定义事件名称,要传的数据)
//父组件
<template>
<div>
<son @send="send"></son>
</div>
</template>
<script>
import son from './son'
export default {
components:{
son
},
methods:{
send(msg){
console.log('父组件收到的消息:'+msg)
},
},
}
</script>
//子组件
<template>
<div>
<button @click="toFather">发送给父组件</button>
</div>
</template>
<script>
export default {
props:['send'],
methods:{
toFather(){
this.$emit('send','子组件的msg')
}
},
}
</script>
三、兄弟组件传值
通过一个中转(bus):
import Vue from ‘vue’
export default new Vue;
A兄弟传值:
import bus from ‘@/common/bus.js’
bus.$emit(‘toBorther’,this.msg)
B兄弟接收:
import bus from ‘@/common/bus.js’
bus.$on(‘toBorther’,(data)=>{
this.msg=data
})
//父组件
<template>
<div class="about">
<!-- 兄弟组件传值 -->
<sister></sister>
<brother></brother>
</div>
</template>
<script>
import sister from '../components/sister'
import brother from '../components/brother'
export default {
data(){
return{
}
},
components:{
sister,
brother
},
}
</script>
//中转(bus.js)
import Vue from 'vue'
export default new Vue;
//A组件(sister.vue)
<template>
<div>
<button @click="send">发送参数</button>
</div>
</template>
<script>
import bus from '@/common/bus.js'
export default {
data(){
return{
msg:"这是A的数据"
}
},
methods:{
send(){//发送参数
bus.$emit('toBorther',this.msg)
}
},
}
</script>
//B组件(borther.vue)
<template>
<div>
{{msg}}
</div>
</template>
<script>
import bus from '@/common/bus.js'
export default {
data(){
return{
msg:'',
}
},
mounted(){
bus.$on('toBorther',(data)=>{//接收参数
this.msg=data
})
},
}
</script>