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>
相关推荐
Felven5 小时前
C. Make Them Equal
c语言·开发语言·前端
智能收银研究所8 小时前
收银系统选型对比:美团、客如云、拉卡拉、收钱吧各适合什么门店
java·前端·数据库
滑动变滚动的蜗牛11 小时前
我发布了自己的个人小程序(诉述洞)
前端·ai编程·全栈
ZYH_060111 小时前
Shell 第一阶段笔记:变量、引号与变量截取
前端·chrome·笔记
YIAN12 小时前
流式 TTS 和普通TTS到底有什么区别?一个文档教会你!
前端·websocket·node.js
掘金安东尼14 小时前
智能体包办工作时,批判性思维怎么办(Addy Osmani 全文转译)
前端·程序员·agent
SameX15 小时前
HarmonyOS ArkTS Canvas 画环形进度条 animateTo + @Watch 驱动重绘 120 行实现
前端
欧雷殿16 小时前
我的 AI 外包实战:用数字员工做项目的一人公司
前端·ai编程·团队管理
狗头大军之江苏分军16 小时前
《潮水漫过十七岁》 补一下,运动会
前端·javascript·后端
狗头大军之江苏分军16 小时前
《潮水漫过十七岁》书都带回去
前端·javascript·后端