简体   繁体   中英

Vue.js reactivity for new object

I am trying to make an object reactive for Vue.js (not present in "data", so no reactive by default).

I came across this guide using Vue.set, but... How do I set an empty object reactive?

An example for explanation:

let app = new Vue({
  el: "#app",

  data: {
    items: [],
  },

methods: {
    setItems: function () {
        this.items[0] = {}; //how to make this reactive?
        Vue.set(this.items[0], 'name', newValue); //newValue should be updated every hour form API response
}

"newValue" is never updated because "{}" is not present in "data", but I don't know how to use Vue.set in this case.

Any idea on how to solve it without adding this code below?

data: {
    items: [{}],
  },

Thank you very much!

How about the following approach?

setItems: function () {
    Vue.set(this.items, 0, { 'name': newValue })
}

Example: https://jsfiddle.net/7mejxybg/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM