[vue3]setup中的顶层属性

265 阅读2分钟

基本语法

知识点说明
<script lang="ts" setup></script>

1、里面代码编译成 setup() 函数的内容,每次创建组件实例都会执行
2、顶层的声明绑定,包括 变量、函数、import导入,在模板中可以直接使用
3、<script setup> 可以和 <script> 一起使用

使用setup的好处

1、代码简洁
2、可以用纯ts声明props和自定义事件
3、运行时性能好
4、IDE推导性能好

组件名规范

知识点说明
<script setup>引入的组件,可以使用 连字符(my-component) 在模板中使用
不过建议使用 大驼峰(MyComponent),有助于区分原生的自定义元素

举个栗子

<script lang="ts" setup>
import MyComponent from './MyComponent.vue'
</script>

<template>
	<MyComponent />
</template>

动态组件

知识点说明
组件通过变量引用,而不是字符串注册,需要用 :is 绑定

举个栗子

<script lang="ts" setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>

<template>
	<component :is="Foo" />
	<component :is="Menus[isActive]" />
	<component :is="isActive ? Foo : Bar" />
</template>

命名空间组件

知识点说明
单个文件导入多个组件,可以使用 带.的组件标签,来引用嵌套在对象属性中的组件

举个栗子

<script lang="ts" setup>
import * as Form from './FormComponents'
</script>

<template>
	<Form.Input>
		<<Form.Label></Form.Label>
	</Form.Input>
</template>

defineExpose

知识点说明
1、defineExpose 不需要导入
2、<script setup> 默认是关闭的,可以通过 defineExpose 暴露组件中的属性,在父组件通过 ref获取和触发

举个栗子

子组件
	import { ref } from 'vue'
	const name = ref('赵今麦')

    const handleName = () => {
        name.value = '杨超越'
    }

    defineExpose({
        name,
        handleName
    })
    
    <div>{{ name || '--' }}</div>

父组件
	import { ref } from 'vue'
	import { Child } from './Child.vue'
	
	const $ChildRef = ref(null)

    const handleChange = () => {
        const name = $ChildRef.value.name
        console.log(name)
        $ChildRef.value.handleName()
    }
    
    <button @click="handleChange">超级变变变</button>
    <Child ref="$ChildRef"/>

useAttrs、useSlots

知识点说明
获取 透传(attrs) 和 插槽内容(slots) 的两种方式
1、模板中通过 attrsattrs 和 slots 访问
2、<script setup> 中通过 useAttrs() 和 useSlots() 访问

举个栗子

父组件
	import Child from './Child.vue'
	
	<Child name="赵今麦" :age="19">
        <div>看太阳的罗绮琦</div>
    </Child>

子组件
	import { useAttrs, useSlots } from 'vue'

    const attrs = useAttrs()
    const slots = useSlots()
    console.log(attrs, slots.default && slots.default())
    
    // 显示内容:赵今麦--19
    <div>{{ $attrs.name }}--{{ $attrs.age }}</div>
    // 显示内容:看太阳的罗绮琦
    <div>{{ $slots.default ? $slots.default()[0].children : '--' }}</div>

顶层await

知识点说明
<script setup> 可以使用 顶层await,代码编译成 async setup()

举个栗子

<script lang="ts" setup>
const { data } = await fetch('urlName', params)
</script>

绝对自律,是通往自由的唯一道路 —— 冬泳怪鸽