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

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

相关推荐
地狱恶犬萨煤耶18 分钟前
JavaScript-小游戏-2048
javascript
爱心发电丶26 分钟前
基于UniappX开发电销APP,实现CRM后台控制APP自动拨号
javascript
地狱恶犬萨煤耶27 分钟前
JavaScript-实现函数方法-改变this指向call apply bind
javascript
地狱恶犬萨煤耶31 分钟前
JavaScript-小游戏-单词消消乐
javascript
q***31141 小时前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
android·前端·后端
q***12531 小时前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found(已解决)
java·前端·maven
攻城狮CSU1 小时前
C# 异步方法
开发语言·前端·c#
tyro曹仓舒1 小时前
干了10年前端,才学会使用IntersectionObserver
前端·javascript
S***y3961 小时前
前端微前端框架对比,qiankun与icestark
前端·前端框架
Wect1 小时前
学习React-DnD:实现多任务项拖拽-useDrop处理
前端·react.js