当前位置: 首页 > news >正文

Vue 中 v-model 的三种使用方式对比与实践

在 Vue 3 中,v-model 是组件双向数据绑定的核心特性。随着 Vue 的版本演进,v-model 的使用方式也在不断优化。本文将基于您提供的代码示例,详细分析三种不同的 v-model 实现方式:基础用法、useVModel Hook(@vueuse/core组件库) 用法和 defineModel 宏用法。

1. 基础 v-model 用法

基础用法是 Vue 3.4 版本之前的标准实现方式,需要手动处理 props 和 emits。

子组件实现 (myChild.vue):

<template><div><ElButton @click="setValue">点击数字增加</ElButton></div>
</template><script setup lang="ts">
import { ref } from "vue";
import { ElButton } from "element-plus";const props = defineProps<{ count: number }>();
const emits = defineEmits(["update:count"]);const setValue = () => {emits("update:count", props?.count + 1);
};
</script>

父组件使用:

<template><div class="w-fuu h-full"><div class="text-center">3.4之前的v-model用法</div><div class="mb-2">{{ count }}---数值</div><myChild v-model:count="count" /></div>
</template><script setup lang="ts">
import { ref } from "vue";
import myChild from "./components/myChild.vue";const count = ref(0);
</script>

特点:

  • 需要显式定义 props 和 emits

  • 通过 emit('update:xxx') 触发更新

  • 兼容性好,适用于所有 Vue 3 版本

  • 代码相对冗长

2. useVModel Hook 用法

useVModel 是一种自定义 Hook(@vueuse/core组件库) 的封装方式,简化了双向绑定的实现。

useVModel源码 :

import type { Ref, UnwrapRef, WritableComputedRef } from 'vue'
import { computed, getCurrentInstance, nextTick, ref, watch } from 'vue'
import type { ToRefs } from 'vue';export type CloneFn<F, T = F> = (x: F) => T;export function isDef<T = unknown>(val?: T): val is T {return typeof val !== 'undefined';
}function cloneFnJSON<T>(source: T): T {return JSON.parse(JSON.stringify(source));
}export interface UseVModelOptions<T, Passive extends boolean = false> {/*** When passive is set to `true`, it will use `watch` to sync with props and ref.* Instead of relying on the `v-model` or `.sync` to work.** @default false*/passive?: Passive;/*** When eventName is set, it's value will be used to overwrite the emit event name.** @default undefined*/eventName?: string;/*** Attempting to check for changes of properties in a deeply nested object or array.* Apply only when `passive` option is set to `true`** @default false*/deep?: boolean;/*** Defining default value for return ref when no value is passed.** @default undefined*/defaultValue?: T;/*** Clone the props.* Accepts a custom clone function.* When setting to `true`, it will use `JSON.parse(JSON.stringify(value))` to clone.** @default false*/clone?: boolean | CloneFn<T>;/*** The hook before triggering the emit event can be used for form validation.* if false is returned, the emit event will not be triggered.** @default undefined*/shouldEmit?: (v: T) => boolean;
}export function useVModel<P extends object,K extends keyof P,Name extends string
>(props: P,key?: K,emit?: (name: Name, ...args: any[]) => void,options?: UseVModelOptions<P[K], false>
): WritableComputedRef<P[K]>;export function useVModel<P extends object,K extends keyof P,Name extends string
>(props: P,key?: K,emit?: (name: Name, ...args: any[]) => void,options?: UseVModelOptions<P[K], true>
): Ref<UnwrapRef<P[K]>>;export function useVModel<P extends object,K extends keyof P,Name extends string,Passive extends boolean
>(props: P,key?: K,emit?: (name: Name, ...args: any[]) => void,options: UseVModelOptions<P[K], Passive> = {}
) {const {clone = false,passive = false,eventName,deep = false,defaultValue,shouldEmit,} = options;const vm = getCurrentInstance();const _emit =emit ||vm?.emit ||vm?.$emit?.bind(vm) ||vm?.proxy?.$emit?.bind(vm?.proxy);let event: string | undefined = eventName;if (!key) {key = 'modelValue' as K;}event = event || `update:${key!.toString()}`;const cloneFn = (val: P[K]) =>!clone ? val : typeof clone === 'function' ? clone(val) : cloneFnJSON(val);const getValue = () =>isDef(props[key!]) ? cloneFn(props[key!]) : defaultValue;const triggerEmit = (value: P[K]) => {if (shouldEmit) {if (shouldEmit(value)) _emit(event, value);} else {_emit(event, value);}};if (passive) {const initialValue = getValue();const proxy = ref<P[K]>(initialValue!);let isUpdating = false;watch(() => props[key!],(v) => {if (!isUpdating) {isUpdating = true;(proxy as any).value = cloneFn(v) as UnwrapRef<P[K]>;nextTick(() => (isUpdating = false));}});watch(proxy,(v) => {if (!isUpdating && (v !== props[key!] || deep)) triggerEmit(v as P[K]);},{ deep });return proxy;} else {return computed<P[K]>({get() {return getValue()!;},set(value) {triggerEmit(value);},});}
}export function useVModels<P extends object, Name extends string>(props: P,emit?: (name: Name, ...args: any[]) => void,options?: UseVModelOptions<any, true>,
): ToRefs<P>
export function useVModels<P extends object, Name extends string>(props: P,emit?: (name: Name, ...args: any[]) => void,options?: UseVModelOptions<any, false>,
): ToRefs<P>
export function useVModels<P extends object, Name extends string, Passive extends boolean>(props: P,emit?: (name: Name, ...args: any[]) => void,options: UseVModelOptions<any, Passive> = {},
): ToRefs<P> {const ret: any = {};for (const key in props) {ret[key] = useVModel(props,key,emit,options as Parameters<typeof useVModel>[3],);}return ret;
}

子组件实现 (ProRadiuSelectSecond.vue):

<template><div class="radio"><divv-for="item in option":key="item?.value":class="{ item_radio: true, active: item.value == checked }"@click="seletItem(item)">{{ item.label }}</div></div>
</template><script lang="ts" setup>
import { useVModel } from "@/utils/useVModel";
import { ref } from "vue";defineOptions({ name: "ProRadiuSelectSecond" });const props = defineProps<{option: { label: string; value: number }[];checked?: number | string;
}>();const emit = defineEmits(["update:checked"]);const checked = useVModel(props, "checked", emit);const seletItem = (val: any) => {if (checked.value == val.value) {checked.value = undefined;return;}checked.value = val.value;
};
</script><style scoped lang="less">样式忽略
@import url("./index.less");
</style>

父组件使用:

<template><div><h1 class="mb-4">useVmodelHooks使用</h1><ProRadiuSelectSecond :option="myOptions" v-model:checked="selset" /></div>
</template><script lang="ts" setup>
import { ref } from "vue";
import { ProRadiuSelectSecond } from "@/components/ProComponents/index";const selset = ref(1);const myOptions = [{label: "香蕉a",value: 1,},{label: "榴莲a",value: 2,},{label: "西瓜a",value: 3,},
];
</script>

特点:

  • 封装了 props 和 emits 的处理逻辑

  • 提供更简洁的响应式变量访问

  • 需要额外引入 useVModel 工具函数

  • 适合在需要复用 v-model 逻辑的场景

3. defineModel 宏用法 (Vue 3.4+)

defineModel 是 Vue 3.4 引入的新特性,极大简化了双向绑定的实现。

子组件实现 (ProRadiuSelect.vue):

<template><div class="radio"><divv-for="item in option":key="item?.value":class="{ item_radio: true, active: item.value == checked }"@click="seletItem(item)">{{ item.label }}</div></div>
</template><script lang="ts" setup>
import { ref } from "vue";defineOptions({ name: "ProRadiuSelect" });const checked = defineModel('checked');const props = defineProps<{ option: { label: string; value: number }[] }>();const seletItem = (val: any) => {if (checked.value == val.value) {checked.value = undefined;return;}checked.value = val.value;
};
</script><style scoped lang="less">
@import url("./index.less");
</style>

父组件使用:

<template><div><h1 class="mb-4" >v-model使用</h1><ProRadiuSelect :option="myOptions" v-model:checked="selset" /></div>
</template><script lang="ts" setup>
import { ref, watch } from "vue";
import { ProRadiuSelect } from "@/components/ProComponents/index";const selset = ref();watch(selset, (newVal, oldVal) => {console.log("newVal:", newVal, "oldVal:", oldVal);
});const myOptions = [{label: "香蕉",value: 1,},{label: "榴莲",value: 2,},{label: "西瓜",value: 3,},
];
</script>

特点:

  • 代码最简洁,一行代码即可实现双向绑定

  • 内置类型推断,开发体验好

  • 需要 Vue 3.4 或更高版本

  • 未来 Vue 官方推荐的方式

三种方式对比

特性基础用法useVModel HookdefineModel 宏
代码简洁度
Vue 版本要求所有所有3.4+
类型支持需要手动需要手动自动推断
额外依赖需要
未来兼容性

最佳实践建议

总结

Vue 3 中的 v-model 实现方式经历了从基础用法到 Hook 封装,再到现在的 defineModel 宏的演进过程。随着 Vue 的不断发展,双向绑定的实现变得越来越简洁和高效。开发者应根据项目实际情况选择合适的方式,在保证代码质量的同时提升开发效率。

  1. 新项目:如果使用 Vue 3.4+,优先选择 defineModel 宏,它提供了最简洁的语法和最佳的类型支持。

  2. 旧项目升级

    • 如果需要保持兼容性,可以使用 useVModel Hook 作为过渡方案

    • 逐步将基础用法迁移到 defineModel

    • 使用uni或taro开发小程序时,不太推荐使用defineModel,兼容性较差

  3. 复杂场景:当需要处理复杂的双向绑定逻辑时,可以考虑使用 useVModel 进行自定义封装。

  4. 类型安全:无论使用哪种方式,都应该优先使用 TypeScript 以获得更好的类型检查和开发体验。

http://www.xdnf.cn/news/528391.html

相关文章:

  • B/S架构和C/S架构的介绍与分析
  • UE 材质几个输出向量节点
  • 嵌入式51单片机:C51
  • Qt—模态与非模态对话框
  • 板凳-------Mysql cookbook学习 (四)
  • 分布式天线系统 (DAS, Distributed Antenna System)
  • 机器学习第十六讲:K-means → 自动把超市顾客分成不同消费群体
  • 三维云展展示效果升级​
  • 5个开源MCP服务器:扩展AI助手能力,高效处理日常工作
  • 【11408学习记录】考研英语辞职信写作三步法:真题精讲+妙句活用+范文模板
  • 在linux平台下利用mingw64编译windows程序
  • UE5在Blueprint中判断不同平台
  • [架构之美]从PDMan一键生成数据库设计文档:Word导出全流程详解(二十)
  • C语言之 比特(bit)、字节(Byte)、字(Word)、整数(Int)
  • ABAP实战案例--获取当前数据由哪个用户锁住
  • 微前端记录
  • MFC 编程中 OnInitDialog 函数
  • YOLOV3 深度解析:目标检测的高效利器
  • vue3与springboot交互-前后分离【验证element-ui输入的内容】
  • w~自动驾驶~合集3
  • Linux内核深入学习(4)——内核常见的数据结构之链表
  • 超小多模态视觉语言模型MiniMind-V 训练
  • Java实现PDF加水印功能:技术解析与实践指南
  • leetcode239 滑动窗口最大值deque方式
  • 阿里云国际站与国内站:局势推进中的多维差异
  • TYUT-企业级开发教程-第四章
  • PyTorch图像建模(图像识别、分割和分类案例)
  • (1-5)Java 常用工具类、
  • 用 CodeBuddy 实现「IdeaSpark 每日灵感卡」:一场 UI 与灵感的极简之旅
  • 【Linux】守护进程