vue3.0记录---<script setup>


<script setup> 是在单文件组件 (SFC) 中使用 组合式 API 的编译时语法糖。相比于普通的 <script>语法,它具有更多优势:

  • 更少的样板内容,更简洁的代码。
  • 能够使用纯 Typescript 声明 props 和抛出事件。
  • 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。
  • 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。

说白了就是对于setup()函数的简写

基本语法用法

要使用这个语法,需要将 setup attribute 添加到

<script setup>
console.log('hello script setup')
</script>

里面的代码会被编译成组件 setup() 函数的内容。这意味着与普通的 <script>只在组件被首次引入的时候执行一次不同,<script setup>中的代码会在每次组件实例被创建的时候执行

组件自动注册

不用在components属性中注册,直接可以使用

<template>
    <Child />
</template>

<script setup>
import Child from './Child.vue'
</script>

数据、方法不需要return

<template>
    <button @click="fun">{{name}}</button>
</template>

<script setup>
import {ref} from 'vue'
const name = ref('张三')
const fun = function(){
	console.log('hello')
}
</script>

defineProps 和 defineEmits

<script setup> 中必须使用definePropsdefineEmitsAPI 来声明propsemits ,它们具备完整的类型推断并且在<script setup>中是直接可用的:

<script setup>
const props = defineProps({
  foo: String
})
// 使用时props.foo取值
const emit = defineEmits(['change', 'delete'])
// 使用时emit('change','参数')
</script>

与普通的script一起使用

<script setup>可以和普通的<script>一起使用。普通的<script>在有这些需要的情况下或许会被使用到:

  • 无法在<script setup>声明的选项,例如 inheritAttrs 或通过插件启用的自定义的选项。
  • 声明命名导出。
  • 运行副作用或者创建只需要执行一次的对象。

两者可以一同使用,但最多分别只能使用一个

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦夏木禾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值