概述

  1. ref 用于定义基本类型的响应数据.
  2. reactive 用于定义对象类型的响应数据.
比较项 ref reactive
适用数据类型 可以是基本类型或者对象类型 只能是对象类型或者数组类型

简单代码示例

ref示例
reactive示例
<template>
  <div class="person">
    <h2>{{ name }}</h2>
    <p>Age: {{ age }}</p>
    <button @click="changeName('JAJA')">Change Name</button>
    <button @click="changeAge(25)">Change Age</button>
  </div>
</template>

<script lang="ts">
  export default {
    name: 'Person',
  }
</script>

<script lang="ts" setup name="Person">
  import { ref } from 'vue';
  // 使用 ref 定义组件的响应式数据
  let name = ref('John Doe');
  let age = ref(30);

  function changeName(newName: string) {
    name.value = newName;
    console.log(`Name changed to: ${name.value}`);
  }

  function changeAge(newAge: number) {
    age.value = newAge;
    console.log(`age changed to: ${age.value}`);
  }
</script>

<style scoped>
  .person {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
  }
</style>
<template>
  <div class="car">
    <h2>一辆 {{ car.brand }} 车价值: {{ car.price }}</h2>
    <button @click="changePrice">修改汽车价值</button>
  </div>
  <br>
  <h2>游戏列表</h2>
  <ul>
    <!-- 使用 v-for 指令遍历游戏列表 -->
    <!-- :key 实质是 v-bind:key -->
    <li v-for="game in games" :key="game.id">
      {{ game.id }} - {{ game.name }}
    </li>
  </ul> 
</template>

<script lang="ts">
  export default {
    name: 'Person',
  }
</script>

<script lang="ts" setup name="Car">
  import { reactive } from 'vue'

  // 数据
  let car = reactive({brand:'奔驰', price: 100});
  // 修改汽车价值
  function changePrice() {
    car.price += 10;
    console.log(`汽车价值修改为: ${car.price}万`);
  }
  let games = [
    { id: 'Game 1', name: 50 },
    { id: 'Game 2', name: 60 },
    { id: 'Game 3', name: 70 }
  ]
</script>

<style scoped>
  .person {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
  }
</style>