Vue3 基础语法指南:响应式系统与 Ref 应用

发布于:2025-03-23 ⋅ 阅读:(80) ⋅ 点赞:(0)
1、Reactive 的深度响应式

1.1、基本用法

vue

<script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  user: {
    name: 'Alice',
    age: 30
  }
})

const increment = () => state.count++
const updateName = () => state.user.name = 'Bob'
</script>

1.2、Todolist 实战

vue

<script setup>
import { reactive } from 'vue'

const state = reactive({
  todos: [
    { id: 1, text: 'Learn Vue3', done: false }
  ],
  newTodo: ''
})

const addTodo = () => {
  state.todos.push({
    id: Date.now(),
    text: state.newTodo,
    done: false
  })
  state.newTodo = ''
}
</script>
2、Ref 的灵活应用

2.1、基础使用

vue

<script setup>
import { ref } from 'vue'

const count = ref(0)
const user = ref({ name: 'Alice' })

const increment = () => count.value++
const updateName = () => user.value.name = 'Bob'
</script>

2.2、Ref vs Reactive

特性 Ref Reactive
适用类型 基本类型 / 对象类型 对象类型
响应式本质 通过.value 访问响应式数据 直接访问响应式数据
深层响应 对象类型自动转为 Reactive 深度响应
性能优化 基本类型更高效 对象类型更高效

使用原则

javascript

// 基本类型
const num = ref(0)

// 浅层次对象
const user = ref({ name: 'Alice' })

// 深层次对象
const complex = reactive({
  a: { b: { c: 0 } }
})

2.3、标签与组件引用

DOM 元素引用

vue

<template>
  <h1 ref="title">Hello Vue3</h1>
  <button @click="updateTitle">Update</button>
</template>

<script setup>
import { ref } from 'vue'

const title = ref<HTMLHeadingElement>(null)
const updateTitle = () => {
  title.value.style.color = 'red'
  title.value.textContent = 'Updated!'
}
</script>

组件实例引用

vue

<!-- 父组件 -->
<template>
  <MyComponent ref="child" />
  <button @click="callChildMethod">Call Child</button>
</template>

<script setup>
import MyComponent from './MyComponent.vue'
import { ref } from 'vue'

const child = ref()
const callChildMethod = () => {
  child.value.sayHello()
  console.log(child.value.count)
}
</script>

<!-- 子组件 -->
<script setup>
import { ref, defineExpose } from 'vue'

const count = ref(0)
const sayHello = () => console.log('Hello!')

defineExpose({
  count,
  sayHello
})
</script>
总结对比
功能点 Setup 函数 Reactive Ref
作用 组件逻辑入口 深度响应式对象 灵活响应式变量
适用场景 所有组合式 API 使用 复杂对象状态管理 基础类型 / 简单对象管理
性能考量 优先使用组合式 API 对象层级越深越推荐 基本类型优先
特殊能力 访问 props/context 自动依赖收集 模板引用

通过合理运用这些特性,可以构建出更高效、更易维护的 Vue3 应用。


网站公告

今日签到

点亮在社区的每一天
去签到