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>
相关推荐
炫饭第一名2 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫2 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊2 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter2 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折2 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_2 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial3 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu3 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu3 小时前
Angular6学习笔记13:HTTP(3)
前端
小码哥_常3 小时前
Kotlin抽象类与接口:相爱相杀的编程“CP”
前端