使用Vue.js和本地存储刷新页面后保持按钮文本状态

时间:2020-04-05 01:38:02

标签: laravel vue.js local-storage

我正在使用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>

1 个答案:

答案 0 :(得分:1)

您正在将item2分配为item道具,该道具是只读的,因为它是作为属性传递的,因此item2保留对同一只读对象的引用。

您可以简单地使用传播语法或Object.assign方法来创建新对象。

item2: {...this.item}

UPDATE:正如您所评论的,如果它是JSON字符串,则只需对其进行解析并将其保留为item2

item2: JSON.stringify(this.item)