我正在使用Vue.js组件和Laravel处理任务列表,并带有一个按钮来将每个任务标记为“完成”或“未完成”。目前,我什至无法更改状态,更不用说在页面刷新后对其进行维护了。控制台日志显示[Vue警告]:挂接的钩子中出现错误:“ TypeError:在严格模式下不允许分配只读属性”。
CompleteButton.vue
<template>
<button type="button" @click="on_order_button_click()">
{{ buttonText }}
</button>
</div>
</template>
<script>
export default {
props: ['userId', 'item'], required: true,
data() {
return {
item2: this.item
}
},
methods: {
on_order_button_click() {
this.item2.is_complete = !this.item2.is_complete;
localStorage.setItem(this.item2.id, this.item2.is_complete);
}
},
mounted() {
var storedState = localStorage.getItem(this.item2.id);
if (storedState) {
this.item2.is_complete = storedState;
}
},
computed: {
buttonText() {
return this.item2.is_complete === true ? "Completed" : "Incomplete";
}
}
};
</script>
index.blade.php
<complete-button user-id="{{ $user->id }}" item="{{ $item}}"></complete-button>
答案 0 :(得分:1)
您正在将item2
分配为item
道具,该道具是只读的,因为它是作为属性传递的,因此item2
保留对同一只读对象的引用。
您可以简单地使用传播语法或Object.assign
方法来创建新对象。
item2: {...this.item}
UPDATE:正如您所评论的,如果它是JSON字符串,则只需对其进行解析并将其保留为item2
。
item2: JSON.stringify(this.item)