✅ Vue 3 响应式写法小抄表(Composition API 实战模板)

发布于:2025-03-17 ⋅ 阅读:(21) ⋅ 点赞:(0)

📦 引入核心响应式工具

import { ref, reactive, computed, watch, toRefs } from 'vue'

1️⃣ 基本类型(string / number / boolean) → 推荐使用 ref()

const username = ref('')
const count = ref(0)
const isLoading = ref(false)

2️⃣ 对象/表单结构 → 推荐使用 reactive()

const form = reactive({
  name: '',
  age: '',
  gender: ''
})

3️⃣ 列表/数组用法

简单数组:const list = ref([])
复杂结构(对象包含数组):
const state = reactive({
  dataList: []
})

4️⃣ 获取 DOM 元素 → 使用 ref()

<template>
  <div ref="boxRef">Hello</div>
</template>

<script setup>
const boxRef = ref(null)

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

5️⃣ 解构 reactive 对象 → 用 toRefs()

const form = reactive({ name: '', age: 18 })
const { name, age } = toRefs(form) // 保持响应式

6️⃣ 计算属性 computed(含 get/set)

const firstName = ref('Tom')
const lastName = ref('Jerry')

const fullName = computed({
  get() {
    return firstName.value + ' ' + lastName.value
  },
  set(val) {
    [firstName.value, lastName.value] = val.split(' ')
  }
})

7️⃣ watch 响应式监听

✔ 监听 ref
watch(count, (newVal, oldVal) => {
  console.log('count变化了', newVal)
})
✔ 监听 reactive 对象内部属性
watch(() => form.name, (newVal) => {
  console.log('姓名改了', newVal)
})

8️⃣ 控制 UI 状态(loading、弹窗等)

const loading = ref(false)
const dialogVisible = ref(false)

function openDialog() {
  dialogVisible.value = true
}
function closeDialog() {
  dialogVisible.value = false
}

9️⃣ 常用组合技巧(混用 ref 和 reactive)

const form = reactive({
  username: '',
  password: ''
})
const btnLoading = ref(false)
const rules = reactive({}) // 表单校验规则

✅ 响应式用法推荐总结表:

场景 推荐方式
单一变量(string/num) ref()
多个表单字段 reactive()
获取 DOM 元素 ref()
解构对象保持响应式 toRefs()
简单数组 ref([])
对象含数组结构 reactive({ list: [] })

💡 附加 Bonus:组合式响应式状态管理(简写版替代 Vuex)

// useStore.js
import { reactive } from 'vue'

export const useStore = () => {
  const state = reactive({
    userInfo: {},
    isLogin: false
  })

  const setUser = (info) => {
    state.userInfo = info
    state.isLogin = true
  }

  return { state, setUser }
}