DoubleM
DoubleM

Reputation: 123

Problem when importing js-cookies in Main.js

I'm trying import js-cookies in my main.js

Main.js

import * as Cookies from "js-cookie";
Vue.use(Cookies)

Using in component

 this.$Cookies.set('name', data.user, { secure: true });

Error

TypeError: Cannot read property 'set' of undefined

what is the problem? I have tried a thousand ways and it still does not work.

Upvotes: 1

Views: 1269

Answers (2)

Larizza Tueros
Larizza Tueros

Reputation: 629

Vue.use(name) is used to install a vue plugin. The package will need an install method that receives a vue instance.

#1 You can use the cookies packages without a plugin importing the module in the component

<script>
import  Cookies from 'js-cookie';
export default {
  methods: {
    addCookie() {
      console.log('adding the cookie');
      Cookies.set('chocolate', 'chookies');
      console.log(Cookies.get());
    }
  }
}
</script>

#2 you can add a VUE plugin and set a Cookies prototype function to the Cookies module. (Prototype vue functions will be available for components, it's standard to prefix them with $).

src/CookiesPlugin.js

import Cookies from 'js-cookie';

const CookiesPlugin = {
  install(Vue, options) {
    Vue.prototype.$Cookies = Cookies;
  }
};

export default CookiesPlugin;

src/main.js

import CookiesPlugin from './CookiesPlugin';
Vue.use(CookiesPlugin);

In the component

this.$Cookies.set('chocolate', 'chookies');
console.log(this.$Cookies.get());

Upvotes: 2

Enrique Chavez
Enrique Chavez

Reputation: 1429

You are using a NOT Vue (Vanilla JS library) library and you are trying to use it as a Vue resource.

Try using this one instead

Upvotes: 0

Related Questions