Nuxt/examples/with-cookies/plugins/cookies.js

35 lines
847 B
JavaScript
Raw Normal View History

2017-08-24 18:37:54 +00:00
import Vue from 'vue'
import Cookie from 'cookie'
import JSCookie from 'js-cookie'
2017-08-24 16:48:31 +00:00
// Called only on client-side
2017-08-24 18:37:54 +00:00
export const getCookies = (str) => {
return Cookie.parse(str || '')
2017-08-24 16:48:31 +00:00
}
/*
** Executed by ~/.nuxt/index.js with context given
** This method can be asynchronous
*/
export default ({ req }, inject) => {
2017-08-24 18:37:54 +00:00
// Inject `cookies` key
// -> app.$cookies
// -> this.$cookies in vue components
// -> this.$cookies in store actions/mutations
inject('cookies', new Vue({
data: () => ({
cookies: getCookies(process.server ? req.headers.cookie : document.cookie)
2017-08-24 18:37:54 +00:00
}),
methods: {
set(...args) {
JSCookie.set(...args)
this.cookies = getCookies(document.cookie)
},
remove(...args) {
JSCookie.remove(...args)
this.cookies = getCookies(document.cookie)
}
}
}))
2017-08-24 16:48:31 +00:00
}