目录
(三)defineProps() 和 defineEmits()
(一)介绍
<script setup>是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的<script>语法,它具有更多优势:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 TypeScript 声明 props 和自定义事件。
- 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
- 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
(二)基本语法
<script setup> 中的代码会在每次组件实例被创建的时候执行
自动注册属性和方法无需返回直接使用: 简化了以往的组合API的必须return的写法,并且有更好的运行时性能。
组件自动注册:无法配置当前组件的名字name项,它会自动以文件名为name。
1.顶层的绑定会被暴露给模板
当使用 <script setup> 的时候,任何在 <script setup> 声明的顶层的绑定 (包括变量,响应式数据,函数声明,以及 import 引入的内容) 都能在模板中直接使用
<script setup>
// 引入组合式api
import { ref } from 'vue';
// 引入组件
import child from './components/child.vue';
// 定义ref数据
let hello = ref('hello')
// 定义函数
function sayHello() {
alert('hello')
}
</script>
<template>
<div id="app">
<p>{{ hello }}</p>
<button @click="sayHello">hello</button>
<child />
</div>
</template>
import导入的函数也能够直接在模板中使用
(三)defineProps() 和 defineEmits()
原先使用props和emit是通过setup()传入的props和context.emit参数接收的,现在setup配置项被取消后,需要通过新的函数进行接收,即defineProps和defineEmits
defineProps():
在app.vue中:
<child msg="hello Vue3!" @sayHello="sayHello" />
在child.vue中:
<script setup>
// 最简单写法
// let props = defineProps(['msg'])
// 定义传入props数据的类型
let props = defineProps({
msg: String
})
</script>
<p>{{ props.msg }}</p>
defineprops没有给props提供设置默认值的方式,因此需要额外借助 withDefaults
编译器宏
defineEmits():
在child.vue中:
<script setup>
let emit = defineEmits(['sayHello'])
</script>
<button @click="emit('sayHello', '12345')">sayHello</button>
(四)useSlots和useAttrs
在 <script setup> 使用 slots 和 attrs 的情况应该是相对来说较为罕见的,因为可以在模板中直接通过 $slots 和 $attrs 来访问它们。在你的确需要使用它们的罕见场景中,可以分别用 useSlots 和 useAttrs 两个辅助函数
<script setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
useSlots 和 useAttrs 是真实的运行时函数,它的返回与 setupContext.slots 和 setupContext.attrs 等价。它们同样也能在普通的组合式 API 中使用
(五) defineExpose()
使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。
目的是把属性和方法暴露出去,可以用于父子组件通信,子组件把属性暴露出去, 父组件用ref获取子组件DOM,子组件暴露的方法或属性可以用dom获取
在child.vue中:
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>
父组件通过ref获取暴露出的数据
在app.vue中:
<child ref="child"
msg="hello Vue3!" @sayHello="sayHello" />
<button
@click="console.log(child, child.a, child.b)">展示获取到的子组件数据</button>
(六)生命周期
选项式的生命周期api方式不能使用了,需要使用组合式的生命周期api格式
如下:
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('-----onMounted-----');
})
</script>