setup语法糖

setup语法糖

为什么要有setup语法糖:

在选择式API中,一个模块涉及到的数据、方法、声明周期,会比较分撒,位置不集中,不利于解读代码,但是组合式API中的setup函数可以将他们组织在一起,提高了代码的可维护性以及复用性,但是每次使用都要写setup函数,还需要将变量返回,所以引入了setup语法糖

setup函数原始写法:

<script>
export default{
	setup(){
		const message = 'This is message'
		const logMessage=()=>{
		console.log(message)
		}
        return{
            message,
            logMessage
		}
	}
}
<script>

setup函数的用法:

setup函数他的执行时机比beforeCreate更早,所以在setup函数中this的返回值是undefind,因此在setup函数中不使用this,

使用setup组件自动注册

注意下面对比

需要手动注册(在选择式API中)

<script>
    import ChildComponent from './ChildComponent.vue'
	export default{
        component:{
            ChildComponent
		}
    }
</script>
<template>
        <ChildComponent />
</template>

自动注册(组合式API)

<script setup>
    import ChildComponent from './ChildComponent.vue'
</script>
<template>
        <ChildComponent />
</template>

一般情况下,会自动注册,但是下面三种情况需要注意

动态组件((需用 resolveComponent))

<script setup>
import { resolveComponent } from 'vue'

const componentName = 'ChildComponent'
const ChildComponent = resolveComponent(componentName)
</script>

<template>
  <component :is="ChildComponent" />
</template>

递归组件(需显式引用自身)

<!-- TreeItem.vue -->
<script setup>
import TreeItem from './TreeItem.vue' // 导入自身

defineProps({
  data: Object
})
</script>
<template>
  <div>
    {{ data.name }}
    <TreeItem 
      v-for="child in data.children" 
      :key="child.id" 
      :data="child" 
    />
  </div>
</template>

全局组件(需通过 app.component 注册)

// main.ts
import { createApp } from 'vue'
import GlobalButton from './components/GlobalButton.vue'

const app = createApp(App)
app.component('GlobalButton', GlobalButton) // 全局注册
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值