setup
一个组件选项,在组件被创建之前,props 被解析之后执行。它是组合式 API 的入口。
<!--父组件-->
<template>
<view>
<HelloWorld msg=" Vite" />
</view>
</template>
<!--子组件 -->
<template>
<view>
<button type="button" @click="addOne">count is: {{ count }}</button>
</view>
</template>
<script >
import { ref } from "vue";
export default {
props: {
msg: String
},
setup(props) {
console.log(props);
const count = ref(0);
let addOne = () => {
console.log(1);
count.value++;
};
return {
count,
addOne
};
}
};
</script>
单文件组件<script setup>
为了方便的使用setup,可以通过<script setup>
,它是在单文件组件 (SFC) 中使用组合式 API的编译时语法糖。相比于普通的 <script>
语法,它具有更多优势:
- 更少的样板内容,更简洁的代码。
- 能够使用纯 Typescript 声明 props 和抛出事件。
- 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。
- 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。
基本使用
要使用这个语法,需要将 setup
attribute 添加到<script>
代码块上:
<script setup>
console.log('hello script setup')
</script>
里面的代码会被编译成组件 setup() 函数的内容。这意味着与普通的 <script> 只在组件被首次引入的时候执行一次不同,<script setup> 中的代码会在每次组件实例被创建的时候执行
。
顶层的绑定会被暴露给模板
当使用 <script setup> 的时候,任何在 <script setup> 声明的顶层的绑定 (包括变量
,函数声明
,以及 import
引入的内容) 都能在模板中直接使用:
<script setup>
import { capitalize } from './helpers'
// 变量
const msg = 'Hello!'
// 函数
function log() {
console.log(msg)
}
</script>
<template>
<div @click="log">{{ msg }}</div>
<div>{{ capitalize('hello') }}</div>
</template>
响应式
响应式状态需要明确使用响应式 APIs
来创建。和从 setup()
函数中返回值一样,ref 值在模板中使用的时候会自动解包:
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click="count++">{{ count }}</button>
</template>
使用组件
<script setup>
范围里的值也能被直接作为自定义组件的标签名使用:
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent />
</template>
将MyComponent
看做被一个变量所引用。如果你使用过 JSX,在这里的使用它的心智模型是一样的。其 kebab-case 格式的 <my-component>
同样能在模板中使用。不过,我们强烈建议使用 PascalCase 格式以保持一致性。同时也有助于区分原生的自定义元素。
-
动态组件
由于组件被引用为变量而不是作为字符串键来注册的,在<script setup>
中要使用动态组件的时候,就应该使用动态的 :is 来绑定:
<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>
<template>
<component :is="Foo" />
<component :is="someCondition ? Foo : Bar" />
</template>
-
命名空间组件
可以使用带点的组件标记,例如 <Foo.Bar> 来引用嵌套在对象属性中的组件。这在需要从单个文件中导入多个组件的时候非常有用:
//在文件夹components创建个index.js文件
import Foo from './foo.vue'
import Bar from './bar.vue'
export {Foo,Bar}
<script setup>
//导入components目录下的index.js文件
import * as Form from "../components"
</script>
<template>
<view>
<Form.Foo/>
<Form.Bar/>
</view>
</template>
与普通的 <script> 一起使用
<script setup> 可以和普通的 <script> 一起使用。普通的 <script> 在有这些需要的情况下或许会被使用到:
无法在 <script setup> 声明的选项,例如 inheritAttrs 或通过插件启用的自定义的选项。
声明命名导出。
运行副作用或者创建只需要执行一次的对象。
<script>
// 普通 <script>, 在模块范围下执行(只执行一次)
runSideEffectOnce()
// 声明额外的选项
export default {
inheritAttrs: false,
customOptions: {}
}
</script>
<script setup>
// 在 setup() 作用域中执行 (对每个实例皆如此)
</script>
顶层 await
<script setup>
中可以使用顶层 await
。结果代码会被编译成 async setup()
:
<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>