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.
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.
Setting the cookie
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.
<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