我们在使用组合式api时,在setup函数里面每次都需要手动暴露大量的状态和方法非常繁琐。我们可以使用 <script setup>
来大幅度地简化代码。
在单文件组件中,我们可以在script 标签上添加一个setup属性,这表示着我们在编写组合式api时不需要再故意写setup函数了。这会为我们省略很多很代码量。
比如 我们声明的响应式变量count
和方法increment
不需要return,可以直接在模版中使用,vue会自动处理暴露问题。
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">
{{ count }}
</button>
</template>
在实际开发中我们基本上都会在组合式 API <script setup>
的语法,大多数 Vue 开发者都会选择这种方式编写组合式api。
这种简约式写法和我们之前setup函数式写法会有些小的区别。
局部组件无需注册,引入即可使用
<script setup>
import { ref} from 'vue'
import Hello from "./Hello.vue"
</script>
<template>
<div>
<div>APP Component</div>
<Hello/>
</div>
</template>
替代setup方法的context参数
在setup函数里面,它为我们提供了 props和context参数。
setup(props,context){
......
}
props可以用来获取组件传值
context: {
attrs: Data;
slots: Readonly<InternalSlots>;
emit: (event: string, ...args: any[]) => void;
expose: (exposed?: Record<string, any>) => void;
}
在简约写法中我们可以使用以下几个参数代替 setup参数props和context的功能
<script setup>
//定义和获取props
const {message} = defineProps(['message'])
//定义emit
const emit = defineEmits(['onClick'])
//获取slots插槽集
const slots = defineSlots()
//定义需要向外暴露的状态和方法
defineExpose([message])
const handelClick = ()=>{
emit("onClick","Hello Vue!")
}
</script>
<template>
<div @click="handelClick">
{{message}}
</div>
</template>
除了这些小区别以外,我们在需要setup里写的组件代码,都可以直接在script标签内进行书写。