Vue组件通讯
1.父→子:通过props传递数据
子组件:在子组件内通过props接收父组件数据
props: ['parentMsg']
父组件:在子组件调用标签中传入父组件数据
<world :parentMsg="parentMsg"></world>
2.子→父:通过事件发送数据
子组件:通过$emit发送自定义事件fire和子组件数据child
<button @click="$emit('fire',child)">发送子数据</button>
父组件:其中world为子组件名称,自定义事件fire被触发后调用父组件的childInfo方法,方法中的参数为接收到的child数据
<world v-on:fire="childInfo"></world>
3.完整代码
父组件:因为子组件是局部注册的,先通过import导入,再在父组件中components注册
<template>
<world v-on:fire="childInfo" :parentMsg="parentMsg"></world>
</template>
<script>
import world from './world'
export default {
name: "HelloWorld",
data() {
return {
parentMsg: "我是父数据"
};
},
methods: {
childInfo: function(event){
alert(event)
}
},
components: {
world
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
子组件:接收父组件数据后可以进行操作,这里直接用插值表达式显示出来
<template>
<div>
<button @click="$emit('fire',child)">发送子数据</button>
<div>{{parentMsg}}(这是父数据)</div>
</div>
</template>
<script>
export default {
name: "world",
data() {
return {
child: "我是子数据"
}
},
props: ['parentMsg']
}
</script>
<style lang="less" scoped>
</style>
浙公网安备 33010602011771号