Why local storage is changing every entry in task list

余生颓废 提交于 2021-02-11 14:15:12

问题


The local storage should only hold state for the task where the completed button has been pressed. Currently when I refresh the page all the tasks are marked as completed.

<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>

回答1:


In your calls to set localstorage, you are setting the item with a key of string 'index', not the index data property of your component. With what you have now, all components are reading from the same localstorage key.

For example, change:

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

To:

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

Also, I don't think the way you are setting a data property equal to a passed property works. I've never seen that before. I think you are just setting your index data property equal to the string literal 'this.itemId'.

I've rewritten your component trying to clean what errors I think there are. Let me know if this works.

<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>



来源:https://stackoverflow.com/questions/62140046/why-local-storage-is-changing-every-entry-in-task-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!