Getting the browser cookie in Vue App
In this tutorial, we are going to learn about how to get a cookie from the browser in Vue using the vue-cookies (npm) package.
Installing the vue-cookies package
The vue-cookies
packages help us to easily get the cookies in a vue app.
Run the following command to install the package.
npm install vue-cookies
Now, open your main.js
file and 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 adds the this.$cookies
object to our root app, so that we can access it inside our vue components <script>
tag.
Getting the cookie
To get a cookie inside the vue component, we need to use the this.$cookies.get()
method by passing a cookie-name as its argument.
Here is an example:
<template>
<div id="app">
<h1>Vue cookies</h1>
<button @click="getCookie">Get Cookie</button> </div>
</template>
<script>
export default {
methods:{
getCookie(){
// it gets the cookie called `username`
const username = this.$cookies.get("username"); console.log(username);
}
}
};
</script>
Note: If you set an
httpOnly
to the response, then you can’t access it inside the vue app.