简单实用vue的案例
时间: 2023-06-29 19:18:41 浏览: 54
以下是一个简单实用Vue.js的案例,用于展示一个待办事项列表,并提供添加、删除和修改待办事项的功能。
HTML代码:
```
<div id="app">
<h1>Todo List</h1>
<ul>
<li v-for="(todo, index) in todos" :key="index">
<span :class="{ completed: todo.completed }">{{ todo.title }}</span>
<button @click="edit(index)">Edit</button>
<button @click="remove(index)">Remove</button>
</li>
</ul>
<div>
<input type="text" v-model="newTodo" placeholder="Add new todo">
<button @click="add">Add</button>
</div>
<div v-if="editing !== null">
<input type="text" v-model="todos[editing].title">
<button @click="save">Save</button>
<button @click="cancel">Cancel</button>
</div>
</div>
```
CSS代码:
```
.completed {
text-decoration: line-through;
}
```
JavaScript代码:
```
new Vue({
el: '#app',
data: {
todos: [
{ title: 'Learn Vue.js', completed: false },
{ title: 'Build a Todo app', completed: true },
{ title: 'Deploy to production', completed: false }
],
newTodo: '',
editing: null
},
methods: {
add() {
this.todos.push({ title: this.newTodo, completed: false });
this.newTodo = '';
},
remove(index) {
this.todos.splice(index, 1);
},
edit(index) {
this.editing = index;
},
save() {
this.editing = null;
},
cancel() {
this.todos[this.editing].title = this.todos[this.editing]._title;
this.editing = null;
}
},
computed: {
remaining() {
return this.todos.filter(todo => !todo.completed).length;
}
},
watch: {
editing(newIndex) {
if (newIndex !== null) {
this.todos[newIndex]._title = this.todos[newIndex].title;
}
}
}
});
```
这段代码实现了一个简单的待办事项列表,使用了Vue.js框架、HTML、CSS和JavaScript。在页面中可以添加、删除和修改待办事项,并显示剩余未完成的事项数。
这个案例简单易懂,适合初学者练习使用Vue.js。