一、要点
1)子组件需要主动发送给父组件 (通过$emit('自定义事件’,‘需要传递的值’))
2)父组件内的子组件标签监听子组件的事件
子组件 child.vue
<template>
<div class="child">
<h5>子组件</h5>
<p>{{msg}}</p>
<button @click="send">发送给父组件</button>
</div>
</template>
<script>
export default {
data(){
return {
msg:'我是子组件的值',
}
},
methods:{
// 子组件值传递给父组件通过 $emit() 自定义事件
send(){
//$emit("自定义事件名称",参数) 参数最后可以通过event获取
this.$emit('sendMsg',this.msg)
},
},
}
</script>
父组件监听子组件的自定义事件
parent.vue
<template>
<div class="parent">
<h5>父组件</h5>
<p>准备接受子组件的值:{{childMsg}}</p>
<!-- 在父组件内的子组件标签上绑定的事件,需要子组件去触发 -->
<vchild @sendMsg='acceptMsg'></vchild>
</div>
</template>
<script>
import vchild from './child'
export default {
data() {
return {
childMsg: '',
}
},
components: {
vchild
},
methods: {
//父组件通过监听事件接收
acceptMsg(msg) {
console.log(msg) //此事就是子组件发送过来的值
this.childMsg = msg
},
}
</script>