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 会自动追踪这些变化并更新相关的视图。
  • 深度嵌套:如果对象有深层次的嵌套结构,并且你需要更新深层次的属性,确保路径正确,否则可能会丢失其他层级的数据。
相关推荐
小满zs21 分钟前
Next.js精通SEO第四章(JSON-LD + web vitals)
前端·seo·next.js
云水一下8 小时前
从零开始!VMware安装Fedora Workstation 44桌面系统完整教程
前端
小码哥_常9 小时前
安卓黑科技:实现多平台商品详情页一键跳转APP
前端
killerbasd9 小时前
还是迷茫 5.3
前端·react.js·前端框架
不会敲代码110 小时前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen10 小时前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦10 小时前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen10 小时前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
千寻girling11 小时前
《 Git 详细教程 》
前端·后端·面试
之歆12 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css