目录
在 Vue 开发中,子组件向父组件传值是一个常见的需求。本文将结合视频内容,详细介绍在 Vue2 中的实现方式,并探讨在 Vue3 中的变化以及给出相应代码示例。
一、Vue2 中子组件传值到父组件的方法
-
清空代码准备环境
- 首先,将上节课的代码清空。父组件中不再向子组件传递数据,只是引入子组件,不做其他操作。子组件中也清空内容,只显示 “父组件” 三个字。
-
子组件操作
- 在子组件中添加一个输入框
<input>
,并使用v-model
绑定一个名为value
的数据。 - 通过
watch
监听value
的变化,当value
发生变化时,使用this.$emit
提交一个自定义事件,事件名称为childInput
,并将变化后的数据作为第二个参数传递。
- 在子组件中添加一个输入框
-
父组件操作
- 在父组件中,通过自定义事件名称接收子组件传递过来的数据。将自定义事件名称(如
childInput
)与一个方法(如getValue
)绑定,方法接收一个参数,这个参数就是子组件传递过来的数据。可以将接收到的数据赋值给父组件中的一个变量,如msg
。
- 在父组件中,通过自定义事件名称接收子组件传递过来的数据。将自定义事件名称(如
以下是 Vue2 的代码示例:
<!-- 父组件 -->
<template>
<div>
父组件
<child-component @childInput="getValue"></child-component>
{{ msg }}
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
msg: '',
};
},
methods: {
getValue(data) {
this.msg = data;
},
},
};
</script>
html
复制
<!-- 子组件 -->
<template>
<div>子组件</div>
</template>
<script>
export default {
data() {
return {
value: '',
};
},
watch: {
value() {
this.$emit('childInput', this.value);
},
},
};
</script>
二、Vue3 中的变化及代码示例
在 Vue3 中,子组件向父组件传值的方式基本与 Vue2 相同,但在语法上有一些变化。
-
子组件操作
- 子组件中的代码与 Vue2 类似,使用
watch
监听数据变化并通过emit
提交自定义事件。
- 子组件中的代码与 Vue2 类似,使用
-
父组件操作
- 在 Vue3 中,可以使用
setup
函数来接收子组件传递过来的数据。在setup
函数中,使用on
方法来监听自定义事件,并将接收到的数据赋值给一个响应式变量。
- 在 Vue3 中,可以使用
以下是 Vue3 的代码示例:
<!-- 父组件 -->
<template>
<div>
父组件
<child-component @childInput="getValue"></child-component>
{{ msg }}
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
setup() {
const msg = ref('');
const getValue = (data) => {
msg.value = data;
};
return {
msg,
getValue,
};
},
};
</script>
<!-- 子组件 -->
<template>
<div>子组件</div>
</template>
<script>
import { watch } from 'vue';
export default {
data() {
return {
value: '',
};
},
setup() {
watch(() => this.value, () => {
this.$emit('childInput', this.value);
});
return {};
},
};
</script>
通过以上方法,无论是在 Vue2 还是 Vue3 中,都可以实现子组件向父组件传值的功能。希望本文对你在 Vue 开发中的传值问题有所帮助。