Working with cookies in vuejs

Hello

I have made a simple infobox with a close button. Once the close button is clicked the infobox should not be shown again next time the user loads the app. It should happen through cookies.
I am currently using js-cookie

So far I made it this way, but I can’t get it to work the right way. I hope someone helps.

html

 <div v-show="closeBox()">                     
     <span style="float:right; color:white; font-size:22px; padding-right:12px;"><a 
 @click="closeBox()" href="#">Close</a></span>
   <p>som info message</p>
 </div>

Javascript:

closeBox(){    
          Cookies.set("cookie", "false");
             var cookie = Cookies.get("cookie");
             return cookie;       
        },

Try:

<template>
 <div v-show="!hasCookie">                     
     <span style="float:right; color:white; font-size:22px; padding-right:12px;"><a 
 @click="closeBox" href="#">Close</a></span>
   <p>som info message</p>
 </div>
</template>
<script>
export default {
 methods: {
  closeBox() {
   Cookies.set("cookie", "false");
  }
 }
 computed: {
  hasCookie() {
    return Cookies.get("cookie") === 'false' ? true : false;
  }
 }
};
</script>
1 Like

Cookies aren’t reactive so you’re going to need a bit of hoop-jumping to get them to work.

<template>
  <div v-show="isBoxShowing">
    ...
    <a @click="closeBox">Close</a>
    ...
  </div>
</template>

<script>
// ... I assume you're importing Cookie here...

export default {
  data () {
    return {
      isBoxShowing: Cookies.get('cookie') !== 'false'
    }
  },

  methods: {
    closeBox () {
      Cookies.set('cookie', 'false')
      this.isBoxShowing = false
    }
  }
}
</script>

I dare say there are libraries that will give you a reactive wrapper for cookies if you want one.

Also, not entirely clear why you’re using v-show rather than v-if.

1 Like

Thank you so much for the answer, it works like a charm. What’s wrong with using v-show, are there better benifites using it?

Thank you so much for your answer it worked fine as well!

v-show will keep the DOM nodes around when the message is hidden. Sometimes that’s useful but in your case they won’t be shown again so they’re just consuming resources for nothing.

1 Like

alright, ill just change it to v-if then, thanks!

@skirtle Is absolutely correct! I totally forgot to push the value into a reactive data prop.

1 Like