Vue3 给 reactive 响应式对象赋值

在 Vue 3 中,你可以使用 reactive 函数创建响应式对象。如果你想给这个响应式对象赋值,可以直接修改其属性。以下是一些示例:

直接修改属性

你可以直接通过点符号或方括号语法来修改响应式对象的属性。

javascript 复制代码
import { reactive } from 'vue';

const form = reactive({
  file: "",
  fileArr: [],
  fileCount: 5,
  content: "",
});

// 直接修改属性
form.file = "newFile.txt";
form.fileArr.push("file1.txt");
form.fileCount = 10;
form.content = "This is the new content.";

使用 Object.assign 进行批量赋值

如果你需要一次性更新多个属性,可以使用 Object.assign

javascript 复制代码
import { reactive } from 'vue';

const form = reactive({
  file: "",
  fileArr: [],
  fileCount: 5,
  content: "",
});

// 使用 Object.assign 进行批量赋值
Object.assign(form, {
  file: "newFile.txt",
  fileArr: ["file1.txt", "file2.txt"],
  fileCount: 10,
  content: "This is the new content."
});

使用展开运算符(Spread Operator)进行批量赋值

你也可以使用展开运算符来进行批量赋值。

javascript 复制代码
import { reactive } from 'vue';

const form = reactive({
  file: "",
  fileArr: [],
  fileCount: 5,
  content: "",
});

// 使用展开运算符进行批量赋值
form = { ...form, ...{
  file: "newFile.txt",
  fileArr: ["file1.txt", "file2.txt"],
  fileCount: 10,
  content: "This is the new content."
}};

注意事项

  • 响应性 :由于 reactive 创建的对象是响应式的,所以当你修改这些属性时,Vue 会自动追踪这些变化并更新相关的视图。
  • 深度嵌套:如果对象有深层次的嵌套结构,并且你需要更新深层次的属性,确保路径正确,否则可能会丢失其他层级的数据。
相关推荐
万少3 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站5 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名8 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫8 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊8 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter8 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折9 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_9 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码19 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial9 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js