我有一个组件,需要显示基于布尔变量的html。我使这个变量与我在localStorage中设置的变量相同。因此,如果我单击foo,我将其设置为false,既作为变量,又在localStorage中。如果单击该条,则将其设置为true。现在,在加载组件之前,我将得到这个变量,并使其与本地变量相同,所以如果我单击foo,当我重新加载组件时,变量为false,因此html应该向我显示foo。但我不明白他为什么给我看酒吧!解释起来有点复杂,我希望您能从代码中理解:
<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>我在stackblitz上附加了一个示例,所以也许您可以进行测试:https://stackblitz.com/edit/vue-b3ieft?file=src%2FApp.vue
发布于 2022-03-29 08:55:43
因为您在localStorage中保存的变量是字符串。当你这样做时:
const boh = localStorage.getItem('boh');
this.isTrue = boh;实际上你得到了:
this.isTrue = 'true';这个字符串总是true。
为了避免这种情况,您可以检查它是否是true字符串:
const boh = localStorage.getItem('boh');
this.isTrue = boh === 'true';发布于 2022-03-29 12:03:42
加到“乔治的答案”上。为了避免不必要的检查,很好的做法是,布尔人在设置本地存储时使用字符串化,而在获取项时解析。
设置
localStorage.setItem("boh", JSON.stringify(false));获取
const boh = JSON.parse(localStorage.getItem('boh'))https://stackoverflow.com/questions/71659063
复制相似问题