我想为我的对象添加一个属性'time',但是有问题
我试过一些方法,比如Vue.set,this.$set
,或者直接添加属性(object.newProperty = 'XXX')
, 但它没有用
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)
}
有人可以帮我解决吗?谢谢
最佳答案
如果没有看到您的完整代码,很难说出问题所在,因为 Vue.set(item, 'time', this.getTime())
是添加属性的正确语法。
这是一个 fiddle ,您的代码将属性 time 添加到项目列表中 https://jsfiddle.net/1vnfjh62/ .也许它会帮助您发现代码中的问题。
编辑 1:
根据您评论中的代码,我认为问题在于您将 allOrderList
设置为服务器中的数组对象。您应该只将服务器中的项目添加到您的 vue.js 数组中。所以你会像这样初始化你的 Vue.js:
data: {
allOrderList: []
}
然后从服务器将项目附加到您的数组:
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)
})
})
你不需要在这里使用 Vue.set(...)
因为它还不是一个 react 对象。
关于javascript - vue中如何给对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653432/