[Vuejs]-Hide HTML div once button is clicked with cookies?

0👍

Here is the answer to my question. Where you can add a cookie to a close/hide button so it won’t show again, unless the user deletes their browser data.

The following is achieved by using js-cookie library

<template>
  <div v-show="isBoxShowing">

    <a @click="closeBox">Close</a>
   
  </div>
</template>

<script>
// here you import the cookie lib
export default {
  data () {
    return {
      isBoxShowing: Cookies.get('cookie') !== 'false'
    }
  },

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

0👍

I see you are trying to hide/close the div when the span is clicked.

  • You need to register the event method in the same vue component.
  • Also, it is better to use reactive state (showBox below) to show/hide the div

watch this example code…

<div v-show="showBox">                     
    <span><a id="closeButton" @click.prevent="closeBox" href="#">Close</a></span>
       <p>som info message</p>
     </div>
data() {
  return: {
    showBox: true
  }
},
methods: {
  closeBox() {
    this.showBox = false;
    Cookies.set("cookie", "false");
    var cookie = Cookies.get("cookie");
        }
          else
         {
        cookie = true
        }
        return cookie;
        ...

0👍

You can do this with vanilla js, css and HTML.
in you’r HTMl:

 <div v-show="closeBox()">                     
    <span><a id="closeButton" @click="closeBox()" href="#">Close</a></span>
       <p id="message">som info message</p>
  </div>

You’r js:

closeBox(){
    let closeButton = document.getElementById("closeButton")
    let message = document.getElementById("message")
    
    if(closeButton.clicked()){  // pseudo code
        message.className += "hide"
        // sets the cookie
       document.cookie = 'cookie=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
    }
}

and finally in you’r css:

.hide {
    display: none;
}

Update

set cookie added in answer.
For more reference on working with cookies using vanilla js follow this link.

Leave a comment