vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue  defineModel

Vue3 新特性defineModel用法如何让 v-model 写法更优雅

作者:编程随想_Code

Vue3.3新增defineModel语法糖,简化v-model双向绑定,子组件通过声明响应式变量直接与父组件绑定,无需props+emit,本文给大家介绍Vue3 新特性defineModel用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

一、前言

在 Vue3.3 版本中,官方新增了一个非常实用的语法糖 —— defineModel。它的主要作用是让我们在组件中更方便地使用 v-model,简化了以往繁琐的写法。
如果你之前写过 Vue2 或 Vue3 的组件,应该对 props + emit 结合 v-model 的写法很熟悉。但这种写法相对麻烦,而 defineModel 正是为了解决这个问题而生的。

二、回顾传统v-model用法

在 Vue3 中,父子组件传递双向绑定一般是这样写的:

子组件(传统写法)

<script setup>
import { defineProps, defineEmits } from 'vue'
const props = defineProps({
  modelValue: String
})
const emit = defineEmits(['update:modelValue'])
function onInput(e) {
  emit('update:modelValue', e.target.value)
}
</script>
<template>
  <input :value="props.modelValue" @input="onInput" />
</template>

父组件

<script setup>
import ChildInput from './ChildInput.vue'
import { ref } from 'vue'
const text = ref('')
</script>
<template>
  <ChildInput v-model="text" />
  <p>父组件里的值:{{ text }}</p>
</template>

可以看到:

三、defineModel的出现

Vue3.3 引入的 defineModel 大大简化了这个流程。它让子组件可以直接声明一个 响应式变量,这个变量就自动和 v-model 绑定。

子组件(使用defineModel)

<script setup>
const modelValue = defineModel()
</script>
<template>
  <input v-model="modelValue" />
</template>

是不是简单很多?

四、defineModel的进阶用法

1. 指定类型

<script setup lang="ts">
const modelValue = defineModel<string>()
</script>

这样在 TS 下会有更好的类型提示。

2. 自定义prop名称

默认情况下,defineModel() 对应的就是 v-model(即 modelValue)。
但如果你想用多个 v-model,也可以给它起名字:

<script setup>
const title = defineModel('title')
const content = defineModel('content')
</script>
<template>
  <input v-model="title" placeholder="标题"/>
  <textarea v-model="content" placeholder="内容"></textarea>
</template>
父组件这样用:
<ArticleEditor v-model:title="postTitle" v-model:content="postContent" />

3. 添加默认值和校验规则

defineModel 也支持和 defineProps 类似的配置:

<script setup>
const modelValue = defineModel({
  type: String,
  default: 'Hello Vue3',
  required: true
})
</script>

这样可以确保绑定的值有默认值,也能做一些简单的类型校验。

五、defineModel的优缺点

优点

缺点

六、适用场景

七、总结

defineModel 是 Vue3.3 之后提供的一个语法糖,它让我们在子组件中使用 v-model 更加简洁高效:

如果你项目的 Vue 版本在 3.3 以上,强烈推荐用起来!

到此这篇关于Vue3 新特性defineModel用法如何让 v-model 写法更优雅的文章就介绍到这了,更多相关vue defineModel 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文