扇贝听力
126.68M · 2026-02-26
Vue3 的 <script setup> 是官方推荐写法,代码更简洁、逻辑更聚合。本文带你真正用好组合式 API。
<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 })
import { computed } from 'vue'
const doubleNum = computed(() => num.value * 2)
<button @click="add">+1</button>
<script setup>
const add = () => {
num.value++
}
</script>
import { onMounted, onUpdated, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件挂载')
})
// 子组件
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
title: String
})
</script>
// 子组件
const emit = defineEmits(['change'])
const handleChange = () => {
emit('change', '新数据')
}
<div ref="box"></div>
<script setup>
import { ref } from 'vue'
const box = ref(null)
onMounted(() => {
console.log(box.value)
})
</script>
<script setup> 优点: