0👍
localStorage.setItem
takes 2 params, name
and value
.
I believe you meant to write the following:
Setting an item in localStorage
localStorage.setItem('item', this.item2)
and retrieving it
localStorage.getItem('item')
A few comments on other parts of your code:
-
this.item2 === true
can be shortened tothis.item2
ifitem2
can never be anything other than a boolean. -
You’re currently only using the value from
localStorage
if it’sfalse
, which it will never be because you’re only ever callingsetItem
with a value oftrue
-
I’m not sure what you’re trying to do with the
item
prop in the top level of the object -
Strongly consider using camelCase for your method names. Follow global conventions
UPDATE:
I think this is what you’re trying to achieve:
on_order_button_click() { // Should probably rename this to `onOrderButtonClick`, the current method name hurts to look at
this.clickedOrderButton = true;
localStorage.setItem('clickedOrderButton', this.clickedOrderButton);
}
created() {
this.clickedOrderButton = localStorage.getItem('clickedOrderButton') === "true";
}
I’ve renamed item2
to clickedOrderButton
. I have no idea why you’d name that variable item2
based on the code that is shown.
There’s also no need to check whether clickedOrderButton
is true
before assigning it to clickedOrderButton
, as it will resolve to false
if it’s not present (or intentionally set to something other than true
) in localStorage
.
Lastly, I’ve replaced mounted
by created
. As you’re not accessing any DOM elements, there’s no need to wait until the component is mounted to run that code
UPDATE#2:
If you have several instances of this component, you’ll need to set use a different name than clickedOrderButton
. You can use a unique identifier per button, which you can pass as a prop from above.
E.g.
props: {
id: { type: String, required: true }
}
...
localStorage.setItem(`clickedOrderButton-${this.id}`, this.clickedOrderButton);
...
localStorage.getItem(`clickedOrderButton-${this.id}`);