子组件:
<template>
<section class="son">
<input v-model="message" />
</section>
</template>
<script>
export default {
data() {
return {
message: '请输入...',
};
},
methods: {},
watch: {
message() {
// 调用父组件传入的自定义方法, 将参数传递给父组件
this.$emit('getMsg', this.message);
},
},
};
</script>
父组件:
<template>
<div class="father">
<h1>父组件</h1>
<!-- 父组件传入一个自定义方法, 以便子组件传递数据 -->
<Son @getMsg="getVal"></Son>
<p>子组件输入的值: {{ childVal }}</p>
</div>
</template>
<script>
import Son from '../components/Son';
export default {
components: {
Son,
},
data() {
return {
childVal: '',
};
},
methods: {
// 接收子组件传过来的messag值
getVal(msg) {
// 将值赋予父组件自身的定义的变量
this.childVal = msg;
},
},
};
</script>
效果: