TypeError: this.$cookies is undefined using vue-cookie

1.1k Views Asked by At

I'm trying use vue cookies, I made all the process to install it

npm install vue-cookies --save

and in my /resources/js/app.js I have

window.Vue = require('vue').default;
var VueCookie = require('vue-cookie');
Vue.use(VueCookie);
this.$cookies.set('test', 'Hello world!', 1);

so, when I load the page I give the next error

TypeError: this.$cookies is undefined    

I tried to solve this in different ways like:

this.$cookies.set(...)
Vue.$cookies.set(...)
this.$cookie.set(...)
Vue.$cookies.set(...)
window.$cookies.set(...)
window.$cookie.set(...)
Vue.prototype.$cookie = VueCookie;

but nothing work and always give the same error :(

1

There are 1 best solutions below

2
tony19 On

You're using this.$cookies outside the Vue context, where this is probably window.

To resolve the issue, replace this.$cookies with Vue.$cookies to set a global cookie, or move this.$cookies to a component method/hook.

Example usage based on the docs:

//...
Vue.use(VueCookies)

// set global cookie
Vue.$cookies.set('theme', 'default');

// set cookie from Vue context
new Vue({
  mounted() {
    this.$cookies.set('theme', 'default');
  }
})