I have a component that needs to display html based on a boolean variable. I make this variable the same as the one I set in the localStorage.
So if I click on foo, I set it to false both as a variable and in the localStorage. If I click on the bar I set it to true.
Now, before loading the component I’m going to get this variable, and I make it the same as the one I have locally, so if I clicked on foo, when I reload the component, the variable is false, and therefore the html should show me foo. but I don’t understand why he shows me bars!!!
It’s a bit complicated to explain I hope you understand from the code:
<template>
<div id="app">
<h2 v-if="!isTrue">FOO</h2>
<h2 v-else>BAR</h2>
<button @click="foo()">FOO</button>
<button @click="bar()">BAR</button>
</div>
</template>
<script>
export default {
name: 'App',
data: function () {
return {
isTrue: null,
};
},
created() {
const boh = localStorage.getItem('boh');
this.isTrue = boh;
console.log('boh', boh);
console.log('isTrue', this.isTrue);
},
methods: {
foo() {
this.isTrue = false;
localStorage.setItem('boh', false);
},
bar() {
this.isTrue = true;
localStorage.setItem('boh', true);
},
},
};
</script>
I am attaching an example on stackblitz so maybe you can do tests:
https://stackblitz.com/edit/vue-b3ieft?file=src%2FApp.vue