前言

Vue3 的 <script setup> 是官方推荐写法,代码更简洁、逻辑更聚合。本文带你真正用好组合式 API。

一、script setup 基本写法

<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

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('组件挂载')
})

六、父传子 props

// 子组件
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
  title: String
})
</script>

七、子传父 emit

// 子组件
const emit = defineEmits(['change'])
const handleChange = () => {
  emit('change', '新数据')
}

八、获取 DOM:ref

<div ref="box"></div>

<script setup>
import { ref } from 'vue'
const box = ref(null)

onMounted(() => {
  console.log(box.value)
})
</script>

总结

<script setup> 优点:

  • 代码更少
  • 无需 return
  • 更好的 TS 支持
  • 逻辑更清晰
本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:alixiixcom@163.com