Start live-server:
$ live-server --ignore=todos.json .
Start json-server:
$ json-server -p 8081 todos.json
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Vue.js todo app</title> | |
<script src="https://unpkg.com/vue"></script> | |
<style> | |
.done { | |
text-decoration: line-through; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="app"> | |
<form @submit.prevent="createTodo"> | |
<input type="text" v-model="newTodo" /> | |
<input type="submit" value="Create new todo" :disabled="newTodo === ''" /> | |
</form> | |
<ul> | |
<li v-for="todo in todos" :key="todo.id" :class="{ | |
done: todo.done | |
}"> | |
<span>{{ todo.text }}</span> | |
<input type="checkbox" v-model="todo.done" @change="toggle(todo)" /> | |
<button @click="deleteTodo(todo)">Delete</button> | |
</li> | |
</ul> | |
</div> | |
<script> | |
class API { | |
constructor(root = 'http://localhost:8081') { | |
this.root = root | |
} | |
async fetchTodos() { | |
const response = await fetch(`${this.root}/todos`) | |
return await response.json() | |
} | |
async createTodo(text) { | |
const response = await fetch(`${this.root}/todos`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify({ | |
text, | |
done: false | |
}) | |
}) | |
return response.json() | |
} | |
async deleteTodo(id) { | |
const response = await fetch(`${this.root}/todos/${id}`, { | |
method: 'DELETE' | |
}) | |
} | |
async setTodoState(id, state) { | |
const response = await fetch(`${this.root}/todos/${id}`, { | |
method: 'PATCH', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify({ | |
done: state | |
}) | |
}) | |
return response.json() | |
} | |
} | |
new Vue({ | |
el: '#app', | |
data: { | |
newTodo: '', | |
todos: [] | |
}, | |
created() { | |
this.api = new API() | |
}, | |
async mounted() { | |
this.todos = await this.api.fetchTodos() | |
}, | |
methods: { | |
async createTodo() { | |
if (this.newTodo === '') return | |
const todo = await this.api.createTodo(this.newTodo) | |
this.todos.push(todo) | |
this.newTodo = '' | |
}, | |
async deleteTodo(todo) { | |
await this.api.deleteTodo(todo.id) | |
this.todos = this.todos.filter(t => t.id !== todo.id) | |
}, | |
async toggle(todo) { | |
await this.api.setTodoState(todo.id, todo.done) | |
} | |
} | |
}) | |
</script> | |
</body> | |
</html> |
{ | |
"todos": [ | |
{ | |
"id": 1, | |
"text": "Create todos server", | |
"done": true | |
}, | |
{ | |
"text": "Code cleanup", | |
"done": false, | |
"id": 2 | |
} | |
] | |
} |
Start live-server:
Start json-server: