【问题标题】:Import JSON object in VueJS and add new items to it在 VueJS 中导入 JSON 对象并向其添加新项目
【发布时间】:2016-03-03 12:43:16
【问题描述】:

在 VueJS 中,我从服务器导入一些 JSON。 在此之后,我将使用 v-for 指令显示数据。

问题是,稍后我想向该 JSON 对象添加额外数据。

这是 PHP 的数据对象生成器示例:

{
"Height": {
    "description": "Height of product in centimeters.",
    "values": {
        "1": {
            "value": "20cm",
            "extra": ""
        },
        "2": {
            "value": "60cm",
            "extra": ""
        }
    }
}
}

这是我的 VueJS 实例:

new Vue({
  el: '#attributes_list',
  data: {
    attributes: {!! $attributes_json !!}
  },

  methods: {
    addAttribute : function(attr) {
      this.attributes[attr].values.new = {value: 'test', extra: 'test2'};
    }

  }
})

以及带有事件的按钮:

<button @click.prevent="addAttribute('Height')">Add</button>

我已经知道它不起作用,因为值不在数组中,所以我无法将新数据推入其中。但是如何向这个对象添加新数据呢?

在服务器端,我无法更改数据输出的格式。 谢谢!

【问题讨论】:

    标签: php json vue.js


    【解决方案1】:

    你应该使用vue的$set方法,

    this.$set('attributes.' + attr + '.values.new', {value: 'test', extra: 'test2'})
    

    http://jsfiddle.net/f7pdf9nx/

    【讨论】:

    • 感谢您的回答!对于其他人,您可能需要在 attr 周围放置括号“[]”。像这样.$set('attributes.["' + attr + '"]', data),以防点语法抛出无效的setter表达式。
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    相关资源
    最近更新 更多