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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 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 - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course