Skip to content

Instantly share code, notes, and snippets.

@padcom
Last active April 27, 2020 16:15
Show Gist options
  • Save padcom/403888831623be2afd013af115548c35 to your computer and use it in GitHub Desktop.
Save padcom/403888831623be2afd013af115548c35 to your computer and use it in GitHub Desktop.
Simplest todo application in Vue.js

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
}
]
}
@padcom
Copy link
Author

padcom commented Apr 27, 2020

Start live-server:

$ live-server --ignore=todos.json

Start json-server:

$ json-server -p 8081 todos.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment