普通视图

发现新文章,点击刷新页面。
昨天 — 2025年11月22日首页

vue3自定义v-model

作者 东华帝君
2025年11月22日 15:46

vue 3.0+

1. v-model='color'不自定义属性名

子组件

  • props.modelValue
  • emits("update:modelValue", color.value)
  1. 通过defineProps()拿到props
  2. 通过defineEmits()拿到emits
  3. 通过emit触发更新update:modelValue---- 当使用v-model=时 子组件拿到的是属性为modelValue 的值,这是固定的
<template>
  <label>颜色:<input v-model="color"  /></label>
</template>
<script setup lang="ts">
import { defineProps, defineEmits, ref } from "vue";

const props = defineProps({
  modelValue: String,
});
const emits = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();
const color = computed({
    get:()=>props.modelValue,
    set:(value:string)=>emits('update:modelValue',value)
})

</script>

父组件 v-model="color"

<script setup lang="ts">
import Child from "@/components/child.vue";
import { ref } from "vue";
const color = ref("red");
</script>

<template>
  <Child v-model="color" />
  <div>color:{{ color }}</div>
</template>

2. v-model='color'自定义属性名

子组件
update:color

<template>
  <label>颜色:<input v-model="color" /></label>
</template>
<script setup lang="ts">
import { defineProps, defineEmits, ref } from "vue";

const props = defineProps({
  color: String,
});
const emits = defineEmits<{
  (e: "update:color", value: string): void;
}>();
const color = computed({
    get:()=>props.modelValue,
    set:(value:string)=>emits('update:modelValue',value)
})

</script>

父组件 v-model:color="color"

<script setup lang="ts">
import Child from "@/components/child.vue";
import { ref } from "vue";
const color = ref("red");
</script>

<template>
  <Child v-model:color="color" />
  <div>color:{{ color }}</div>
</template>

vue 3.4+

子组件

<template>
  <label>颜色:<input v-model="color" /></label>
</template>
<script setup lang="ts">
import { defineModel } from "vue";

const color = defineModel({type:String})

父组件

<script setup lang="ts">
import Child from "@/components/child.vue";
import { ref } from "vue";
const color = ref("red");
</script>

<template>
  <Child v-model="color" />
  <div>color:{{ color }}</div>
</template>
❌
❌