Vue3 组合式 API(setup + script setup)实战

前言

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 支持
  • 逻辑更清晰
相关推荐
xiaofeichaichai12 小时前
Webpack
前端·webpack·node.js
问心无愧051313 小时前
ctf show web入门111
android·前端·笔记
唐某人丶13 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界13 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌13 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel14 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia31115 小时前
https连接传输流程
前端·面试
徐小夕15 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
梦梦代码精15 小时前
2026年PHP开源商城系统实测对比:架构、多商户、商用授权,谁才是真·省心?
vue.js·docker·架构·开源·代码规范