setup语法糖
组合式 API:setup()
一、概述
<script setup>语法糖简化了组合式API(compositionApi)的必须返回(return)的写法,有更好的运行时性能。- 使用方式
<template>
<div></div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
</script>
组件核心 API 的使用
一、组件自动注册
在 script setup 中,引入的组件可以直接使用,无需再通过components进行注册,并且无法指定当前组件的名字,自动以文件名为主,不用再写name属性了。
<template>
<Child />
</template>
<script lang="ts" setup>
import Child from "@/components/Child.vue";
</script>
二、defineProps:用来接收父组件传来的 props
通过defineProps指定当前 props 类型,获得上下文的props对象。
<script lang="ts" setup>
import { defineProps } from "vue";
let props = defineProps({
test: {
type: String,
default: "111"
}
});
console.log(props);
</script>
三、defineEmits:声明由组件触发的自定义事件
<template>
<div></div>
</template>
<script lang="ts" setup>
import { defineEmits } from "vue";
let emits = defineEmits(["test"]);
console.log(emits);
//触发事件
emits("test", 11)
</script>
四、useAttrs() 和 useSlots()
$attrs或useAttrs()
<template>
<div>
<div v-bind="$attrs">child</div>
</div>
</template>
<script lang="ts" setup>
import { useAttrs } from "vue";
const attrs = useAttrs();
</script>
“透传 attribute”指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者 v-on 事件监听器。最常见的例子就是 class、style 和 id。
$slots或useSlots()
<script lang="ts" setup>
import { useSlots } from "vue";
const slots = useSlots();
</script>
通常用于手写渲染函数。
五、defineExpose 组件暴露出自己的属性
传统的写法,我们可以在父组件中,通过 ref 实例的方式去访问子组件的内容,但在 script setup 中,该方法就不能用了,setup 相当于是一个闭包,除了内部的 template模板,谁都不能访问内部的数据和方法。
child.vue
<script lang="ts" setup>
import { defineExpose, ref } from "vue";
const test = ref("test");
defineExpose({
test
});
</script>
parent.vue
<template>
<child ref="childRef"></child>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import child from "./child.vue";
// 首先需要通过 typeof 得到其类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型:
const childRef = ref<InstanceType<typeof child> | null>(null);
onMounted(() => {
console.log(childRef.value.test); //获取子组件暴露出来的方法
});
</script>