javascript – How to set cookie in vuejs?

javascript – How to set cookie in vuejs?

You could use the vue-cookie or vue-cookies npm package.
You can set a cookie in the created method.

created() {
   this.$cookie.set(keyName, keyValue, expiring time)
}

You can also do it in a plain JavaScript without using extensions.

Lets say you want to store a token with expiry of 24 hours inside axios POST response.

axios
  .post(url, dataToSend)
  .then(function (response) {
    if (response.status == 200) {
      let d = new Date();
      d.setTime(d.getTime() + 1 * 24 * 60 * 60 * 1000);
      let expires = expires= + d.toUTCString();
      document.cookie =
        Token= + response.data.Token + ; + expires + ;path=/;
    }
  })
  .catch(function (error) {
    console.log(error);
  });

javascript – How to set cookie in vuejs?

Use vue-cookies

To use:

<script src=https://unpkg.com/[email protected]/vue-cookies.js></script>
<script>
  $cookies.set(cookie_name, cookie_value);
</script>

Leave a Reply

Your email address will not be published.