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>
相关推荐
Bigger3 小时前
Tauri (26)——托盘图标总对不上系统主题?一行 Template Image 搞定
前端·rust·app
kyriewen6 小时前
面试官问你:“AI 能写 80% 的代码了,公司为什么还需要你?”
前端·javascript·面试
甲维斯6 小时前
又升级咯!坦克大战2026,科技与复古并存!
前端·人工智能·游戏开发
搬砖的码农9 小时前
(08)为什么我的 Agent 一跑后台服务就卡死
前端·agent·ai编程
飘尘9 小时前
前端转全栈(Java 后端)必须要知道的:开发中的锁机制与分布式并发控制
前端·后端·全栈
亲亲小宝宝鸭9 小时前
前端性能监控:web-vitals
前端·性能优化·监控
陆枫Larry9 小时前
可滚动页面背景填不满:`height: 100vh` vs `min-height: 100vh`
前端
Patrick_Wilson9 小时前
Squash Merge 的血缘陷阱:为什么删掉的代码又活了过来
前端·git·程序员
kyriewen10 小时前
今天的科技圈,全在抢英伟达的饭碗
前端·面试·ai编程