外观
Vue3-setup
680字约2分钟
2024-06-13
Vue3-setup
setup
setup是Vue3新的配置项。Composition API使用的容器。组件中所用到的:数据、方法、计算属性、监视等等,均配置在setup中。
特点:
setup函数返回的对象中的内容,可直接在模板中使用。setup中访问this是undefined。避免在setup中使用thissetup函数会在beforeCreate之前调用,它是“领先”所有钩子执行的。
基本使用
<template>
<div class="hello">
{{ msg }} {{total}}
<button @click="clickChange">Click</button>
</div>
</template>
<script lang="ts">
export default {
name: "demo",
setup() {
let msg = "Hello Vue3"; // 直接定义的数据不是响应式
let total = 1; // 直接定义的数据不是响应式
function clickChange() { // 直接定义的数据不是响应式
msg = "hello Vue3, change!";
total++;
console.log(total,msg) // 输出 2,hello Vue3, change! ;3,hello Vue3, change!;
}
return { msg, total, clickChange }; // 需要把模板使用的数据返回
},
};
</script>
<style scoped>
</style>提示
注意:上面示例中,点击按钮发现页面没有改变,如果打印数据,会发现数据已经改变。因为直接定义的数据不是响应式的,需要使用ref()或reactive()`定义响应式。
返回值
- 若返回一个对象:则对象中的:属性、方法等,在模板中均可以直接使用。
- 若返回一个函数:则可以自定义渲染内容(很少使用),代码如下:
setup(){
return ()=> 'Hello Vue3' //页面会直接显示 Hello Vue3
}setup与data和methods
OptionAPI中的data和methods能和setup同时存在,换句话说,OptionAPI与CompositionAPI可以存在使用。
data和methods能够通过this读取到setup中定义的数据和方法,因为setup函数会在beforeCreate之前调用,比data执行要早(只能获取setup暴露出来的数据和方法)。- 相反,在
setup中获取不到data和methods的数据和方法。
总结
Vue2的配置(data、methos......)中可以访问到setup中的属性、方法。- 但在
setup中不能访问到Vue2的配置(data、methos......)。 - 如果与
Vue2冲突,则setup优先。
setup 简写
setup函数有一个语法糖,这个语法糖,可以让我们把setup独立出去。
- 不用在写
setup方法 - 不用自己
return各个数据和方法。
<template>
<div class="hello">
{{ msg }}
</div>
</template>
<script lang="ts">
export default {
name: "demo",
};
</script>
<script setup lang="ts">
let msg = "Hello Vue3";
</script>使用vite-plugin-vue-setup-extend插件可以省略第一个<script>标签里声明的组件name。让页面只存在一个<script>标签。
下载插件
npm install vite-plugin-vue-setup-extend -D配置插件
import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
export default defineConfig({
plugins: [ VueSetupExtend() ]
})简写优化
<template>
<div class="hello">
{{ msg }}
</div>
</template>
<script setup lang="ts" name="demo">
let msg = "Hello Vue3";
</script>