vue3自定义v-model

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

子组件

  • props.modelValue
  • emits("update:modelValue", color.value)
  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({
  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>
相关推荐
剪刀石头布啊7 小时前
vue-react为何要虚拟dom
前端
剪刀石头布啊7 小时前
ahooks常用的一些库,我们使用一下
前端
剪刀石头布啊8 小时前
从git更新本地提交记录到更新已经推送到远端记录
前端
Flynt10 小时前
axios 被投毒半年后,我把 npm 的"安全防线"实测了一遍:最信任的 SHA512 是安慰剂
前端·npm·node.js
excel10 小时前
Base62 和 Base64 有什么区别?
前端
风骏时光牛马11 小时前
大模型底层架构与AI源码深度剖析
前端
掘金挖土12 小时前
前端手摸手跑路之 AI 应用开发(九)
前端·后端
中文呀15 小时前
三维 GIS 离线缓存实战:逆向 CesiumOfflineCache,并亲手为它补上"自动更新"能力
前端
前进前进前进15 小时前
TRAE 全链路实战:做了一个警示牌一键生成器:纯 Canvas、单文件、零依赖
前端