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

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

相关推荐
LuciferHuang16 分钟前
震惊!三万star开源项目竟有致命Bug?
前端·javascript·debug
GISer_Jing17 分钟前
前端实习总结——案例与大纲
前端·javascript
天天进步201521 分钟前
前端工程化:Webpack从入门到精通
前端·webpack·node.js
姑苏洛言1 小时前
编写产品需求文档:黄历日历小程序
前端·javascript·后端
知识分享小能手2 小时前
Vue3 学习教程,从入门到精通,使用 VSCode 开发 Vue3 的详细指南(3)
前端·javascript·vue.js·学习·前端框架·vue·vue3
姑苏洛言2 小时前
搭建一款结合传统黄历功能的日历小程序
前端·javascript·后端
hackchen2 小时前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
你的人类朋友3 小时前
🤔什么时候用BFF架构?
前端·javascript·后端
知识分享小能手3 小时前
Bootstrap 5学习教程,从入门到精通,Bootstrap 5 表单验证语法知识点及案例代码(34)
前端·javascript·学习·typescript·bootstrap·html·css3