1. v-model='color'不自定义属性名
子组件
props.modelValue- emits("
update:modelValue", color.value)
- 通过
defineProps()拿到props - 通过
defineEmits()拿到emits - 通过
emit触发更新update:modelValue---- 当使用v-model=时 子组件拿到的是属性为modelValue的值,这是固定的
js
<template>
<label>颜色:<input v-model="color" @input="changeColor" /></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 = ref(props.modelValue ?? '')
const changeColor = () => {
emits("update:modelValue", color.value);
};
</script>
<style></style>
父组件 v-model="color"
js
<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'自定义属性名
子组件
props.color- emits("
update:color", color.value)
html
1. 通过`defineProps()`拿到props
2. 通过`defineEmits()`拿到emits
3. 通过`emit`触发更新`update:modelValue`---- 当使用`v-model=`时 子组件拿到的是属性为`modelValue`的值,这是固定的
```js
<template>
<label>颜色:<input v-model="color" @input="changeColor" /></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 = ref(props.color ?? '')
const changeColor = () => {
emits("update:color", color.value);
};
</script>
父组件 v-model:color="color"
html
<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>