Vue 子组件传值到父组件详解

目录

Vue 子组件传值到父组件详解

一、Vue2 中子组件传值到父组件的方法

二、Vue3 中的变化及代码示例


在 Vue 开发中,子组件向父组件传值是一个常见的需求。本文将结合视频内容,详细介绍在 Vue2 中的实现方式,并探讨在 Vue3 中的变化以及给出相应代码示例。

一、Vue2 中子组件传值到父组件的方法

  1. 清空代码准备环境

    • 首先,将上节课的代码清空。父组件中不再向子组件传递数据,只是引入子组件,不做其他操作。子组件中也清空内容,只显示 “父组件” 三个字。
  2. 子组件操作

    • 在子组件中添加一个输入框<input>,并使用v-model绑定一个名为value的数据。
    • 通过watch监听value的变化,当value发生变化时,使用this.$emit提交一个自定义事件,事件名称为childInput,并将变化后的数据作为第二个参数传递。
  3. 父组件操作

    • 在父组件中,通过自定义事件名称接收子组件传递过来的数据。将自定义事件名称(如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 相同,但在语法上有一些变化。

  1. 子组件操作

    • 子组件中的代码与 Vue2 类似,使用watch监听数据变化并通过emit提交自定义事件。
  2. 父组件操作

    • 在 Vue3 中,可以使用setup函数来接收子组件传递过来的数据。在setup函数中,使用on方法来监听自定义事件,并将接收到的数据赋值给一个响应式变量。

以下是 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 开发中的传值问题有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值