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>
相关推荐
fruge1 小时前
搭建个人博客 / 简历网站:从设计到部署的全流程(含响应式适配)
前端
光影少年1 小时前
css影响性能及优化方案都有哪些
前端·css
呆呆敲代码的小Y1 小时前
2025年多家海外代理IP实战案例横向测评,挑选适合自己的
前端·产品
q***3752 小时前
爬虫学习 01 Web Scraper的使用
前端·爬虫·学习
v***5652 小时前
Spring Cloud Gateway
android·前端·后端
b***59432 小时前
分布式WEB应用中会话管理的变迁之路
前端·分布式
q***21602 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
顾安r2 小时前
11.21 脚本 网页优化
linux·前端·javascript·算法·html
q***T5833 小时前
GitHub星标20万+的React项目,学习价值分析
前端·学习·react.js