reactive函数

作用:把对象和数组这类复合数据类型数据变成响应式数据。

案例:渲染学生列表并实现新增学生功能。

在 Vue2 的内容中讲过渲染学生列表案例,本节使用 Vue3 实现新增学生功能,代码如下。

<template>
  <div>
    <ul>
      // 2. 渲染学生列表
      <li v-for="(item, i) in stuList" :key="i">
        {{ item.id }}--{{ item.name }}
      </li>
    </ul>
    <input type="text" v-model="nameMsg" />
    <button @click="addStu">新增</button>
  </div>
</template>

<script>
import { ref, reactive } from "vue";

export default {
  setup() {
    // 1. 使用 reactive 定义响应式学生列表
    var stuList = reactive([
      { id: 1, name: "小明" },
      { id: 2, name: "小红" },
      { id: 3, name: "小强" }
    ]);
    // 使用 ref 定义响应式数据(v-model 双向绑定数据)
    var nameMsg = ref("");
    var addStu = () => {
      stuList.push({ id: stuList.length + 1, name: nameMsg.value });
      nameMsg.value = "";
    };
    return {
      stuList,
      nameMsg,
      addStu
    };
  }
};
</script>

代码解析如下。

  • Vue3 程序运行速度快,有一部分原因是其功能都是按需导入的,例如想使用哪个函数就对该函数进行按需导入,本案例用到了 ref 函数和 reactive 函数。

  • reactive 函数的作用是把数组和对象变成响应式数据。

import { ref, reactive } from "vue";