【问题标题】:Maintaining button text state after page refresh using Vue.js and local storage使用 Vue.js 和本地存储在页面刷新后维护按钮文本状态
【发布时间】:2020-07-17 02:31:58
【问题描述】:

我正在使用 Vue.js 组件和 Laravel 处理任务列表,并使用一个按钮将每个单独的任务标记为“完成”或“未完成”。目前我什至无法让它改变状态,更不用说在页面刷新后维护它了。控制台日志显示 [Vue warn]: Error in mounted hook: "TypeError: Assignment to read-only properties is not allowed in strict mode"。

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>

【问题讨论】:

    标签: laravel vue.js local-storage


    【解决方案1】:

    您将item2 分配为item 属性,它是只读的,因为它作为属性传递,所以item2 保持对同一个只读对象的引用。

    您可以简单地使用扩展语法或Object.assign 方法来创建一个新对象。

    item2: {...this.item}
    

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

    item2: JSON.stringify(this.item)
    

    【讨论】:

    • 感谢您的回答。如果我尝试将“item”作为对象传递,我会得到 [Vue warn]: Invalid prop: type check failed for prop“item”。预期的对象,在控制台日志中获得值为“{”id”:3,...的字符串
    • @jsmith 然后进行 JSON 解析 item2: JSON.parse(this.item)
    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多