by Sai gowtham

How to set a cookie in Vue App

In this tutorial, we are going to learn about how to set a cookie to the webpage in vue app using the vue-cookies package.

Installing the vue-cookies package

Vue cookies package helps us to easily set and get cookies in our vue project.

Run the following command to install it.

npm install vue-cookies

Now, open your main.js file add the following (highlighted) configuration.

main.js
import Vue from "vue";
import VueCookies from 'vue-cookies';import App from "./App.vue";

Vue.use(VueCookies);
new Vue({
  render: h => h(App)
}).$mount("#app");

This injects the this.$cookies object to our root app, so that we can access it inside our vue component instance.

To set a cookie, we need to call the this.$cookies.set() method by passing a cookie-name, cookie-value as arguments.

Here is an example, that sets a cookie to the webpage by clicking the Set Cookie button.

App.vue
<template>
  <div id="app">
     <h1>Vue cookies</h1>
     <button @click="setCookie">Set Cookie</button>  </div>
</template>

<script>
export default {
   methods:{
     setCookie(){
         // it sets the cookie called `username`
       this.$cookies.set("username","gowtham");     }
   }
};
</script>

You can also set the cookie expiration time like this.

this.$cookies.set("username","gowtham","1d");

This above cookie will expire in one day.

For more options like path, domain name, secured, etc visit this url.

You can also get the cookie, by calling a this.$cookies.get() method with cookie-name as its argument.

this.$cookies.get("username"); // gowtham

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course