使用vue3的setup语法糖语法
时间: 2025-04-29 14:47:13 浏览: 49
### 使用 Vue 3 Setup 语法糖
Vue 3 的 `setup` 函数提供了一种更简洁的方式来编写组合式 API 逻辑。通过使用 `<script setup>` 语法糖,可以进一步简化模板中的代码结构并提高可读性。
#### 基本用法
当使用 `<script setup>` 时,所有的声明都会自动暴露给模板和其他选项,无需显式返回对象:
```html
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello World')
</script>
```
这种方式使得组件更加直观易懂[^1]。
#### 处理 Props 和 Emit
对于处理属性 (`props`) 和事件发射 (`emit`),可以直接解构它们而不需要像传统方式那样定义 `setup` 函数参数:
```html
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>
<script setup>
import { defineProps, defineEmits, ref } from 'vue'
// 解构 props
const { count } = defineProps(['count'])
// 定义 emit 并调用
const emit = defineEmits(['update'])
function increment() {
emit('update', count + 1)
}
</script>
```
这不仅减少了样板代码的数量,还提高了开发效率[^2]。
#### 组件间的通信
为了实现父子组件之间的数据共享或者状态管理,在子组件内部可以通过 `provide/inject` 来完成依赖注入操作:
```html
<!-- Parent Component -->
<template>
<child-component />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
import { provide, reactive } from 'vue'
const state = reactive({
user: 'John Doe',
})
provide('state', state) // 提供全局变量
</script>
<!-- Child Component -->
<template>
<p>User Name: {{ state.user }}</p>
</template>
<script setup>
import { inject } from 'vue'
const state = inject('state') // 注入父级提供的变量
</script>
```
这种模式非常适合构建大型应用,因为它允许开发者轻松地管理和传递复杂的状态树.
阅读全文
相关推荐














