Vue3 基础语法指南:Setup 函数详解
1、Setup 的使用
1.1、基本使用
vue
<script setup>
// 组件逻辑写在此处
import { ref } from 'vue'
const count = ref(0)
const increment = () => count.value++
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>
1.2、Setup 执行时间
- 执行顺序:
setup
>beforeCreate
>created
- 特性:
- 无法访问
this
(this
为undefined
) - 可以访问 props 和 context
- 无法访问
- 底层原理:
javascript
export default { setup(props, context) { // 组件初始化逻辑 } }
1.3、Vue2.x 混合使用规范
- 单向访问:
- Vue2.x 的
data/methods/computed
可访问 setup 中的属性 - setup 无法访问 Vue2.x 的配置项
- Vue2.x 的
- 推荐模式:
vue
<script> export default { data() { return { msg: 'vue2' } }, methods: { log() { console.log(this.msg) } } } </script> <script setup> import { ref } from 'vue' const count = ref(0) </script>
1.4、Setup 语法糖
vue
<!-- 不写setup函数 -->
<script setup lang="ts" name="MyComponent">
import { ref } from 'vue'
const count = ref(0)
</script>
<!-- 配置组件名的两种方式 -->
<script name="MyComponent"></script>
<script setup>/* 业务逻辑 */</script>
扩展配置:
- 安装插件:
npm i vite-plugin-vue-setup-extend -D
- 配置
vite.config.ts
:typescript
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import VueSetupExtend from 'vite-plugin-vue-setup-extend' export default defineConfig({ plugins: [vue(), VueSetupExtend()] })