如何将 Vue 包装的对象转换为普通对象 [英] How to convert a Vue-wrapped object to a normal object

查看:91
本文介绍了如何将 Vue 包装的对象转换为普通对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将object类型的数据变量赋值给一个普通变量

I need to assign the data variable of type object to a normal variable

const myVue = new Vue({
  el: '#myVue',
  data: {
    vars: {}, // show Form
  },
  methods: {
    assign_vars() {
      const new_vars = this.vars;
    },
  },
});

html

<input type="text"  v-model="vars.name" >

我需要 new_vars 就像这样:

new_vars: { name: 'test' }

但结果是 new_vars 拥有 Vue 创建的所有属性

but what happens is new_vars is having all the attributes that Vue creates

推荐答案

Vue 将其观察到的数据包装在一个特殊的对象中以有效地观察变化(这就是启用反应性的原因).在大多数用例中,您不需要解包对象,但如果您需要解包,这里有几个方法:

Vue wraps its observed data in a special object to efficiently observe changes (this is what enables reactivity). In most use cases you won't need to unwrap the object, but in case you do, here are a couple of methods:

const unwrapped = JSON.parse(JSON.stringify(this.vars));

这是 Evan You 在此处建议的方法.它甚至适用于深度嵌套的对象,只要类型可以与 JSON(字符串、数字、布尔值、对象和数组)相互转换.如果您的数据包含其他内容(例如日期),您将需要另一种方法.

This is the method suggested by Evan You here. It works well even for deeply nested objects, as long as the types can be converted to and from JSON (strings, numbers, booleans, objects, and arrays). If your data contains something else (e.g. dates), you'll need another approach.

const unwrapped = { ...this.vars }

这适用于浅层对象,即使它们包含非原始对象.

This works well for shallow objects, even if they contain non-primitives.

如果您有一个包含非原始值的深度嵌套对象,您需要编写一个函数来递归地解包其子对象.

If you have a deeply nested object containing non-primitive values, you'll need to write a function that recursively unwraps its sub-objects.

这篇关于如何将 Vue 包装的对象转换为普通对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆