自定义组件的v-model

在这里插入图片描述

要使子组件修改 v-model 的值时,父组件也能感知到变化,你需要在子组件中实现对 v-model 的支持。v-model 在 Vue 中实际上是语法糖,它会将 v-model 绑定的属性和 input 事件结合起来。

以下是如何在子组件中实现对 v-model 的支持的步骤:

定义 v-model 绑定的属性:在子组件中,定义一个 props 用于接收 v-model 的值。

触发 input 事件:在子组件中,当需要更新值时,触发 input 事件来通知父组件值已更改。

以下是一个简单的示例:

父组件

<template>
  <div>
    <test v-model="count"></test>
    <div class="card">
      <button type="button" @click="count++">count is {{ count }}</button>
    </div>
  </div>
</template>

<script>
import Test from './Test.vue';

export default {
  components: { Test },
  data() {
    return {
      count: 0
    };
  }
};
</script>

子组件(Test.vue)

<template>
  <div>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  props: {
    modelValue: Number
  },
  methods: {
    increment() {
      this.$emit('update:modelValue', this.modelValue + 1);
    }
  }
};
</script>

说明:
在子组件中,我们定义了一个 modelValue 的 prop,它是 v-model 绑定的值。
当我们在子组件中执行 increment 方法时,我们通过 this.$emit(‘update:modelValue’, newValue) 触发了一个 update:modelValue 事件,这样父组件才能接收到子组件中 modelValue 的更新。
在 Vue 3 中,v-model 默认使用 modelValue 作为 prop 名称和 update:modelValue 作为事件名称。
vue3用法
父组件

<template>
  <div>
    <Test v-model:count="count" />
    <div class="card">
      <button type="button" @click="count++">count is {{ count }}</button>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import Test from './Test.vue';

export default {
  components: { Test },
  setup() {
    const count = ref(0);

    return {
      count
    };
  }
};
</script>

子组件:

<template>
  <div>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { defineComponent, toRefs } from 'vue';

export default defineComponent({
  props: {
    modelValue: {
      type: Number,
      default: 0
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const { modelValue } = toRefs(props);

    function increment() {
      emit('update:modelValue', modelValue.value + 1);
    }

    return {
      increment
    };
  }
});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值