项目初始化
- 在一个新建的文件夹下运行cmd
vue create todo
- 关闭eslint自动检查
yarn run serve
前期准备 创建工程和组件
- 在compoments目录下创建3个vue文件作为组件复用
components/TodoHeader.vue - 复制标签和类名
<template>
<ul class="todo-list">
<!-- completed: 完成的类名 -->
<li class="completed" >
<div class="view">
<input class="toggle" type="checkbox" />
<label>任务名</label>
<button class="destroy"></button>
</div>
</li>
</ul>
</template>
<script>
export default {
}
</script>
components/TodoFooter.vue - 复制标签和类名
<template>
<footer class="footer">
<span class="todo-count">总计:<strong>数量值</strong></span>
<ul class="filters">
<li>
<a class="selected" href="javascript:;" >全部</a>
</li>
<li>
<a href="javascript:;">未完成</a>
</li>
<li>
<a href="javascript:;" >已完成</a>
</li>
</ul>
<button class="clear-completed" >清除已完成</button>
</footer>
</template>
<script>
export default {
}
</script>
App.vue中引入和使用
<template>
<section class="todoapp">
<!-- 除了驼峰, 还可以使用-转换链接 -->
<todo-header></todo-header>
<todo-main></todo-main>
<todo-footer></todo-footer>
</section>
</template>
<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
import "./styles/base.css"
import "./styles/index.css"
export default {
components: {
TodoHeader,
TodoMain,
TodoFooter,
},
};
</script>
Tips 页面组件根元素添加类名todoapp
循环展示
App.vue
<todo-main :list="list"></todo-main>
export default {
data() {
return {
list: [
{ id: 100, name: "吃饭", isDone: true },
{ id: 201, name: "睡觉", isDone: false },
{ id: 103, name: "打豆豆", isDone: true },
],
};
}
};
TodoMain.vue
<template>
<ul class="todo-list">
<!-- completed: 完成的类名 -->
<li :class="{ completed: item.isDone }" v-for="item in list" :key="item.id">
<div class="view">
<input class="toggle" type="checkbox" v-model="item.isDone" />
<label>{{ item.name }}</label>
<button class="destroy"></button>
</div>
</li>
</ul>
</template>
<script>
export default {
props: ["list"]
};
</script>
<style>
</style>
添加功能
TodoHeader.vue
<template>
<header class="header">
<h1>todos</h1>
<input id="toggle-all" class="toggle-all" type="checkbox" >
<label for="toggle-all"></label>
<input
class="new-todo"
placeholder="输入任务名称-回车确认"
v-model="name"
@keydown.enter="down"
/>
</header>
</template>
<script>
export default {
data(){
return {
name: ""
}
},
methods: {
down(ev){
this.$emit("add", this.name)
this.name = ""
}
}
}
</script>
App.vue
<todo-header @add="addFn"></todo-header>
methods: {
// ...省略了原来的方法
addFn(name){
this.list.push({
id: Date.now(),
name,
isDone: false
})
}
}
删除功能
App.vue - 传入自定义事件等待接收要被删除的id或索引
<todo-main :list="list" @del="delFn"></todo-main>
methods: {
delFn(id) {
// 把id过滤掉
this.list = this.list.filter((item) => item.id !== id);
},
},
TodoMain.vue - 把id传回去实现删除(想好数据在哪里, 就在哪里删除)
<button class="destroy" @click="del(item.id)"></button>
methods: {
del(id) {
// console.log(id)
this.$emit("del", id);
},
},
注意⚠️:通过子传父删除,以免影响后续不同状态下数据的删除操作