Update example to use inject

This commit is contained in:
Sébastien Chopin 2017-08-24 20:37:54 +02:00
parent 1a6a183e43
commit 42f2a59fd2
2 changed files with 45 additions and 25 deletions

View File

@ -17,34 +17,39 @@
</table>
<h2>Add a new cookie</h2>
<form @submit.prevent="addCookie">
<input type="text" v-model="cookie.key" placeholder="Key" class="key"/>:
<input type="text" v-model="cookie.value" placeholder="Value" class="value"/>
<input type="text" v-model="newCookie.key" placeholder="Key" class="key"/>:
<input type="text" v-model="newCookie.value" placeholder="Value" class="value"/>
<button type="submit">Add</button>
</form>
</div>
</template>
<script>
import { cookies, refreshCookies } from '~/plugins/cookies'
import Cookies from 'js-cookie'
export default {
data() {
return {
cookies,
cookie: { key: '', value: '' }
data: () => ({
newCookie: {
key: '',
value: ''
}
}),
computed: {
cookies () {
return this.$cookies.cookies
}
},
methods: {
addCookie() {
if (!this.cookie.key || !this.cookie.value) return
Cookies.set(this.cookie.key.replace(/\s/g, '-'), this.cookie.value)
this.cookies = refreshCookies()
this.cookie.key = this.cookie.value = ''
// Make sure the cookie is not empty
if (!this.newCookie.key || !this.newCookie.value) return
// Sanitize the key to avoid spaces
const cookieKey = this.newCookie.key.replace(/\s/g, '-')
// Add the cookie
this.$cookies.set(cookieKey, this.newCookie.value)
// Reset newCookie data
this.newCookie.key = this.newCookie.value = ''
},
removeCookie(key) {
Cookies.remove(key)
this.cookies = refreshCookies()
this.$cookies.remove(key)
}
}
}

View File

@ -1,19 +1,34 @@
import cookie from 'cookie'
export let cookies
import Vue from 'vue'
import Cookie from 'cookie'
import JSCookie from 'js-cookie'
// Called only on client-side
export const refreshCookies = () => {
cookies = cookie.parse(document.cookie)
return cookies
export const getCookies = (str) => {
return Cookie.parse(str || '')
}
/*
** Executed by ~/.nuxt/index.js with context given
** This method can be asynchronous
*/
export default ({ isServer, req }) => {
// We update the cookies variable
// So we can read it into our page with: import { cookies } from '~/plugins/cookies.js'
cookies = cookie.parse(isServer ? req.headers.cookie : document.cookie)
export default ({ isServer, req }, inject) => {
// Inject `cookies` key
// -> app.$cookies
// -> this.$cookies in vue components
// -> this.$cookies in store actions/mutations
inject('cookies', new Vue({
data: () => ({
cookies: getCookies(isServer ? req.headers.cookie : document.cookie)
}),
methods: {
set(...args) {
JSCookie.set(...args)
this.cookies = getCookies(document.cookie)
},
remove(...args) {
JSCookie.remove(...args)
this.cookies = getCookies(document.cookie)
}
}
}))
}