实验性方法, 未发布
使用方法
普通写法
两件事:
- 注册一个组件
- 导出一个字符串给template使用
<script>
import { ref, defineComponent } from 'vue';
import Card from "./components/Card.vue"; // 导入组件
export default defineComponent {
// 注册组件
components: {
Card
},
setup(){
const msg = ref('script setup')
return { msg }
}
}
</script>
启用script setup
用法: 在script便签上添加setup关键字即可
- 组件自动注册
- 属性和方法无需return, 直接使用
<script setup>
import { ref} from 'vue';
import Card from "./components/Card.vue"; // 导入组件
const msg = ref('script setup')
</script>
核心API
props使用
通过defineProps制定当前props类型, 获取该组件的props
import { defineProps } from 'vue'
const props = defineProps({
title: String,
content: {
type: String,
require: true
}
})
emit使用
通过defineEmit定义当前组件的事件, 并通过返回上下文执行emit
import { defineEmit } from 'vue'
const emit = defineEmit( ['change', 'click'] )
emit('change')
slots和attrs使用
可以通过useContext从上下文中获取slots和attrs, 不过提案通过后, 废除了该语法, 被拆分成useSlots和useAttrs
useAttrs 可以是用来获取 attrs 数据的(也就是非 props 的属性值)。
useSlots 通过 API 的命名也能了解它是用来获取插槽数据的。
// 旧
import { useContext } from 'vue' const { slots, attrs } = useContext()
// 新
import { useAttrs, useSlots } from 'vue'
const attrs = useAttrs()
const slots = useSlots()
defineExpose API
在标准组件写法里,子组件的数据都是默认隐式暴露给父组件的,但在 script-setup 模式下,所有数据只是默认 return 给 template 使用,不会暴露到组件外,所以父组件是无法直接通过挂载 ref 变量获取子组件的数据。
如果要调用子组件的数据,需要先在子组件显示的暴露出来,才能够正确的拿到,这个操作,就是由 expose 来完成。
expose 也是 context 的一个组件成员,
原来的用法,是从 useContext 里导出:
// 导入 useContext 组件
import { useContext } from "vue";
// 启用expose组件
const { expose } = useContext();
// 定义一个想提供给父组件拿到的数据
const msg: string = "Hello World!";
// 显示暴露的数据,才可以在父组件拿到
expose({
msg,
});
新增API defineExpose
// 导入 defineExpose 组件
import { defineExpose } from "vue";
// 定义数据
const msg: string = "Hello World!";
// 暴露给父组件
defineExpose({
msg,
});
这样, 父组件就可以通过定义ref变量去获取子组件暴露出来的api了
顶级await的支持
不需要async再配合await使用, 这种情况下, 组件的setup会自动变成async setup
<script setup>
import { defineComponent } from "vue";
export default defineComponent {
const post = await fun1('/api/getNums').then( r => r)
}
</script>
转换成标准组件的写法就是
<script>
import { defineComponent } from "vue";
export default defineComponent {
async setup(){
const post = await fun1('/api/getNums').then( r => r)
return { post }
}
}
</script>