I'm trying to code in Vue js a text which changes it's color on a click and saves it's state in a cookie. It works good on the first visit (no cookie), color is changing properly, but after refreshing color always turns green. I thought there's a problem with cookie, so I displayed it's value (true/false) in a different and it's working properly. Only color doesn't work.
I've used that cookie library -> https://www.npmjs.com/package/vue-cookies
Video with the problem -> https://streamable.com/ky2l1z
<body>
<div id="app">
<h1 v-bind:class='{cookieColor: color}'>{{ color }}</h1>
<h1 v-bind:class='{cookieColor: color}'>COLOR</h1>
<button @click="setCookie">CHANGE COLOR</button>
</div>
<script>
//CHECKS IF COOKIE EXISTS
var cookieCheck = $cookies.get('isDark');
if(cookieCheck === 'undefined'){
cookieCheck = false;
console.log('COOKIE DOESNT EXIST');
}else{
console.log("COOKIE EXISTS")
}
new Vue({
el: '#app',
data: {
color: cookieCheck,
},
methods: {
setCookie(){
this.color = !this.color;
$cookies.set('isDark', this.color);
var cookieCheck = $cookies.get('isDark');
console.log(this.color);
}
},
})
</script>
<style>
h1{
color:black;
}
.cookieColor{
color: rgb(157, 207, 157);
}
</style>
CodePudding user response:
Try parsing the string value to Boolean using JSON:
var cookieCheck = $cookies.get('isDark');
if (cookieCheck === 'undefined') {
cookieCheck = false;
console.log('COOKIE DOESNT EXIST');
} else {
console.log("COOKIE EXISTS")
// if it exists parse the value
cookieCheck = JSON.parse(cookieCheck)
// Check its type
console.log(typeof cookieCheck)
// >> boolean
}