vue3自定义v-model
2025年11月22日 15:46
vue 3.0+
1. v-model='color'不自定义属性名
子组件
props.modelValue- emits("
update:modelValue", color.value)
- 通过
defineProps()拿到props - 通过
defineEmits()拿到emits - 通过
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>