前言
Vue3 的 <script setup> 是官方推荐写法,代码更简洁、逻辑更聚合。本文带你真正用好组合式 API。
一、script setup 基本写法
xml
<script setup>
// 直接写逻辑,无需 export default
import { ref, reactive, computed } from 'vue'
const msg = ref('Hello Vue3')
</script>
<template>
<div>{{ msg }}</div>
</template>
二、响应式数据
-
ref:基础类型(string/number/boolean) -
reactive:对象 / 数组const num = ref(0) const user = reactive({ name: '张三', age: 20 })
三、计算属性 computed
javascript
import { computed } from 'vue'
const doubleNum = computed(() => num.value * 2)
四、方法与事件
xml
<button @click="add">+1</button>
<script setup>
const add = () => {
num.value++
}
</script>
五、生命周期
javascript
import { onMounted, onUpdated, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件挂载')
})
六、父传子 props
xml
// 子组件
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
title: String
})
</script>
七、子传父 emit
javascript
// 子组件
const emit = defineEmits(['change'])
const handleChange = () => {
emit('change', '新数据')
}
八、获取 DOM:ref
xml
<div ref="box"></div>
<script setup>
import { ref } from 'vue'
const box = ref(null)
onMounted(() => {
console.log(box.value)
})
</script>
总结
<script setup> 优点:
- 代码更少
- 无需 return
- 更好的 TS 支持
- 逻辑更清晰