我正在创建一个使用本地存储中的值更新props的组件。道具是具有多个布尔属性的对象(例如 this.globalStates.repeat = false )。因为我有多个道具需要更新,所以我为任何作为参数提供的道具创建了一个方法:
mounted(){
this.loadLocalData(this.globalStates, "states")
this.loadLocalData(this.globalSettings, "settings")
},
methods: {
loadLocalData(object, localVariable){ // 'object' receives a prop, 'localVariable' must refer to a string in localStorage (localStorage stores strings only).
const loadedObject = JSON.parse(localStorage.getItem(localVariable)) // Turn localStorage string into JSON object
if (loadedObject && typeof loadedObject === "object"){
for (let item in object){ // iterate through the prop and update each property with the one in loadedObject
object[item] = loadedObject[item] // Why does this work!?
}
}
}
},
现在这确实有效,没有错误或警告。我不明白为什么。通常当我尝试直接修改道具时,Vue会向我发出警告:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
而不是object[item] = loadedObject[item]
我尝试了以下内容,但实际上失败了:
const u = 'update:' + object + '.' + item
this.$emit(u, loadedObject[item] )
这样做的正确方法是什么?
答案 0 :(得分:0)