首页 > 解决方案 > 为什么本地存储正在更改任务列表中的每个条目

问题描述

本地存储应该只保存已按下完成按钮的任务的状态。目前,当我刷新页面时,所有任务都标记为已完成。

<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>
</div>
</template>

<script>
export default {

props: 'itemId', required: true,
data() {
    return {
        index: 'this.itemId',
        status: ''
    }
},
methods: {
on_order_button_click() {
  this.status = !this.status;
  localStorage.setItem('index', this.status);
}

},
mounted() {

this.status = localStorage.getItem('index') === "true";
},
computed: {
buttonText() {
  return this.status === true ? "Completed" : "Complete";
},
 order_button_style() {
  return this.status === true
    ? "btn btn-danger"
    : "btn btn-primary";
}

}

};
</script>

标签: javascriptlaravelvue.jslocal-storagelocal

解决方案


在设置 localstorage 的调用中,您使用字符串“索引”键设置项目,而不是组件的索引数据属性。有了你现在所拥有的,所有组件都从同一个本地存储键读取。

例如,更改:

mounted() {
    this.status = localStorage.getItem('index') === "true";
},

至:

mounted() {
    this.status = localStorage.getItem(this.index) === "true";
},

另外,我认为您将数据属性设置为等于传递的属性的方式不起作用。我以前从未见过。我认为您只是将索引数据属性设置为等于字符串文字'this.itemId'

我已经重写了您的组件,试图清除我认为存在的错误。让我知道这个是否奏效。

<template>
    <button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
        {{ buttonText }}
    </button>
</template>

<script>
export default {
    props: {
        itemId: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            status: false,
        }
    },
    methods: {
        on_order_button_click() {
            this.status = !this.status;
            localStorage.setItem(this.itemId, this.status);
        }
    },
    mounted() {
        this.status = localStorage.getItem(this.itemId) === "true";
    },
    computed: {
        buttonText() {
            return this.status === true ? "Completed" : "Complete";
        },
        order_button_style() {
            return this.status === true ?
                "btn btn-danger" :
                "btn btn-primary";
        }

    }

};
</script>


推荐阅读