jeremy.Wu
jeremy.Wu

Reputation: 23

How to add properties to a object in vue

I want to add a property 'time' to my object, but there is something wrong

I have tried some way, just like Vue.set, this.$set, or add properties in a directly way (object.newProperty = 'XXX'), but it didn't work

this.allOrderList.forEach((item) => {
     this.$set(item, 'time', this.getTime())
     Vue.set(item, 'time', this.getTime())
     item.time = this.getTime()
})

getTime () {
     return Math.round(Math.random()*(60 - 30)+30)
}

Can someone help me to resolve it ? thank you

Upvotes: 2

Views: 21955

Answers (1)

Hazza
Hazza

Reputation: 6591

Without seeing your full code it is hard to say what the issue is as Vue.set(item, 'time', this.getTime()) is the correct syntax for adding properties.

Here is a fiddle with your code adding the property time to a list of items https://jsfiddle.net/1vnfjh62/. Maybe it will help you see the problem in your code.

EDIT 1:

From the code in your comment I think the issue is that you are setting allOrderList to be the array object from your server. You should just add items from the server to your vue.js array. So you'd initialise your Vue.js like so:

data: {
    allOrderList: []
}

Then append items to your array from the server:

    this.axios.get('/order/refresh').then((res) => {         
      res.data.data.forEach((item) => { 
        item.created_at = timestampToTime(item.created_at) 
        item.time = this.getTime()
        this.allOrderList.push(item)
      })
    })

You don't need to use Vue.set(...) here as it is not yet a reactive object.

Upvotes: 5

Related Questions