TodoList案例目录
main.js
import Vue from 'vue'
import App from './App.vue'
// 关闭vue的生产提示
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
// 安装全局事件总线
beforeCreate() {
// $bus相当于一个事件中心
Vue.prototype.$bus = this
}
}).$mount('#app')
App.vue
<template>
<div class="todo-container">
<div class="todo-wrap">
<!-- 向子组件传递一个函数 -->
<SearchHeader @addItem="addItem" />
<!--使用全局事件总线,就可以不用这些:delItem="delItem"
:changeStatus="changeStatus" -->
<SearchList :dataList="doList" />
<SearchFooter
:doList="doList"
@checkedStatus="checkedStatus"
@delDone="delDone"
/>
</div>
</div>
</template>
<script>
import SearchHeader from "./components/SearchHeader.vue";
import SearchFooter from "./components/SearchFooter.vue";
import SearchList from "./components/SearchList.vue";
// 订阅与发布相关插件
import pubsub from "pubsub-js";
export default {
components: {
SearchHeader,
SearchFooter,
SearchList,
},
data() {
return {
// 在本地内存中读取相关的数据
/* doList: [
{ id: "01", title: "吃饭", done: true },
{ id: "02", title: "睡觉", done: false },
{ id: "03", title: "打代码", done: true },
], */
// 第一次使用时,内存中没有存有数据,会报错
// JSON.parse(null)==null,然后再将null传给子组件,子组件使用时就会报错
// doList: JSON.parse(localStorage.getItem("doList")),
// 前面如果为真就用,不为真就用后面的
doList: JSON.parse(localStorage.getItem("doList")) || [],
pubId: 0,
};
},
methods: {
// 子传父结合父传子
// 添加新任务
addItem(x) {
// console.log("从header来的数据:" + x);
// 在doList前面添加新任务
this.doList.unshift(x);
// console.log(this.doList);
},
// 改变任务状态
changeStatus(id) {
// 遍历doList
this.doList.forEach((item) => {
// 根据id查找对应的任务
if (item.id == id) {
// 改变状态
item.done = !item.done;
}
});
},
// 删除指定的任务
/* delItem(v) {
this.doList = this.doList.filter((i) => {
return i.id != v;
});
}, */
// 消息发布和订阅的回调函数是可以接收两个参数的,第一个参数是发布的消息的名字,第二参数才是发布的数据
// 但第一个参数一般不用,所以用_来占个位
delItem(_, v) {
this.doList = this.doList.filter((i) => {
return i.id != v;
});
},
// 改变任务状态
checkedStatus(done) {
this.doList.forEach((v) => {
v.done = done;
});
},
// 清除已完成的任务
delDone() {
// 返回过滤结果为true的数据
this.doList = this.doList.filter((v) => {
// 当done为true时,!true为false,结果为false,不能返回,直接淘汰
return !v.done;
});
},
// 编辑任务
updateTitle(id, title) {
// 遍历doList
this.doList.forEach((item) => {
// 根据id查找对应的任务
if (item.id == id) {