Add with-cookies example

This commit is contained in:
Sebastien Chopin 2017-08-24 18:48:31 +02:00
parent 7738d0c0af
commit c9e77337b3
5 changed files with 118 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# Hello World with Nuxt.js
https://nuxtjs.org/examples

View File

@ -0,0 +1,9 @@
module.exports = {
head: {
title: 'Nuxt-Cookies',
meta: [
{ content: 'width=device-width,initial-scale=1', name: 'viewport' }
]
},
plugins: ['~/plugins/cookies']
}

View File

@ -0,0 +1,13 @@
{
"name": "hello-nuxt",
"dependencies": {
"cookie": "^0.3.1",
"js-cookie": "^2.1.4",
"nuxt": "latest"
},
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start"
}
}

View File

@ -0,0 +1,74 @@
<template>
<div>
<h1>Cookies</h1>
<table>
<thead>
<tr>
<th>Key</th><th>Value</th><th></th>
</tr>
</thead>
<tbody>
<tr v-for="(value, key) in cookies">
<td>{{ key }}</td>
<td>{{ value }}</td>
<td><button @click="removeCookie(key)">Remove</button></td>
</tr>
</tbody>
</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"/>
<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: '' }
}
},
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 = ''
},
removeCookie(key) {
Cookies.remove(key)
this.cookies = refreshCookies()
}
}
}
</script>
<style scoped>
table {
text-align: left;
}
th, td {
padding-right: 10px;
}
input.key {
width: 50px;
}
input.value {
width: 100px;
}
input, button {
border: 1px #ddd solid;
background: white;
padding: 5px;
}
button[type="submit"] {
margin-left: 5px;
}
</style>

View File

@ -0,0 +1,19 @@
import cookie from 'cookie'
export let cookies
// Called only on client-side
export const refreshCookies = () => {
cookies = cookie.parse(document.cookie)
return cookies
}
/*
** 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)
}