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
      }
    }

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

相关推荐
胡gh4 小时前
页面卡成PPT?重排重绘惹的祸!依旧性能优化
前端·javascript·面试
胡gh4 小时前
简单又复杂,难道只能说一个有箭头一个没箭头?这种问题该怎么回答?
javascript·后端·面试
言兴4 小时前
# 深度解析 ECharts:从零到一构建企业级数据可视化看板
前端·javascript·面试
山有木兮木有枝_4 小时前
TailWind CSS
前端·css·postcss
烛阴5 小时前
TypeScript 的“读心术”:让类型在代码中“流动”起来
前端·javascript·typescript
杨荧5 小时前
基于Python的农作物病虫害防治网站 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python
Moment6 小时前
毕业一年了,分享一下我的四个开源项目!😊😊😊
前端·后端·开源
程序视点7 小时前
Escrcpy 3.0投屏控制软件使用教程:无线/有线连接+虚拟显示功能详解
前端·后端
silent_missile7 小时前
element-plus穿梭框transfer的调整
前端·javascript·vue.js
专注VB编程开发20年7 小时前
OpenXml、NPOI、EPPlus、Spire.Office组件对EXCEL ole对象附件的支持
前端·.net·excel·spire.office·npoi·openxml·spire.excel