Getting the browser cookie in Vue App

Getting the browser cookie in Vue App

In this post we will give you information about Getting the browser cookie in Vue App. Hear we will give you detail about Getting the browser cookie in Vue AppAnd how to use it also give you demo for it if it is necessary.

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.

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 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:

App.vue
&lt;template&gt;  &lt;div id="app"&gt;     &lt;h1&gt;Vue cookies&lt;/h1&gt;     &lt;button @click="getCookie"&gt;Get Cookie&lt;/button&gt;  &lt;/div&gt;&lt;/template&gt;&lt;script&gt;export default {   methods:{     getCookie(){         // it gets the cookie called 'username'      const username = this.$cookies.get("username");      console.log(username);     }   }};&lt;/script&gt;

Note: If you set an httpOnly to the response, then you can’t access it inside the vue app.

Hope this code and post will helped you for implement Getting the browser cookie in Vue App. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US