Vue3-新特性defineOptions和defineModel

defineOptions

问题:用了<script setup>后,就无法添加与其平级的属性了,比如定义组件的name或其他自定义的属性。

为了解决这一问题,引入了defineProps与defineEmits这两个宏,但这只解决了props与emits这两个属性。如果要定义其他的平级属性,还是得回到最原始的用法--就再添加一个普通的<script>标签。这样就会存在两个<script>标签,让人无法接受。

所以在Vue3.3中新引入了defineOptions宏。顾名思义,主要是用来定义Option API的选项。可以用defineOptions定义任意的选项,props、emits、expose、slots除外(因为这些可以使用defineXXX来做到)

复制代码
<script setup>
import { defineOptions } from 'vue'
defineOptions({
  name: 'Foo',//组件重命名
  inheritAttrs: false,
  //...更多自定义属性
})
</script>

defineModel

实验型,快速实现双向绑定,简化v-model

在Vue3中,自定义组件上使用v-model,相当于传递一个modelValue属性,同时触发update:modelValue事件

复制代码
<Child v-model="isVisible">
//相当于
<Child :modelValue="isVisible" @update:modelValue="isVisible=$event">

我们需要先定义props,再定义emits。其中有许多重复的代码。如果需要修改此值,还需要手动调动emit函数

父组件:

复制代码
<template>
  <inputModel v-model="txt"></inputModel>{{ txt }}
</template>

<script setup>
import inputModel from '@/components/inputModel.vue'
import { ref } from 'vue'
const txt = ref(100)
</script>

子组件:

复制代码
<script setup>
import { defineProps, defineEmits } from 'vue'
defineProps({
  modelValue: String
})
const emit = defineEmits(['update:modelValue'])
</script>
<template>
  <div>
    <input type="text" :value="modelValue" @input="e => emit('update:modelValue', e.target.value)">
  </div>
</template>
<style scoped>
input {
  width: 14rem;
  height: 2rem;
}
</style>

使用defineModel改进后的子组件:

复制代码
<script setup>
import { defineModel } from 'vue'
const modelValue = defineModel()
</script>
<template>
  <div>
    <input type="text" :value="modelValue" @input="e => modelValue = e.target.value">
  </div>
</template>

因为这是实验型,所以还需要配置一些东西才能生效

打开vite.config.js文件加入以下语句:

复制代码
    {
      script: {
        defineModel: true
      }
    }

写完后,需要重新启动这个项目才能生效

相关推荐
沐言人生3 小时前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
怕浪猫4 小时前
NVIDIA 全产品谱系与演进
javascript·面试·github
excel5 小时前
为什么 super 中能接收到 resolve 和 reject?
前端
Flynt6 小时前
AI 生成的界面,能放心点吗?我把 Google A2UI 的三层防线拆开测了一遍
前端·google·agent
前端混子7 小时前
我用 AI 做了个「禾月小历」,一套代码跑微信小程序和 H5
前端
IT_陈寒8 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
小帅不太帅8 小时前
一年一次黑五,为了买软件真省钱,我做了个开源小站
前端·人工智能·github
JavaGuide10 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021710 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户693717500138410 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github