尚硅谷——TodoList案例最终版

本文详细介绍了基于Vue.js的TodoList项目,包括main.js的配置,App.vue的主体结构,SearchHeader、SearchList、SearchItem及SearchFooter组件的实现,展示了完整的项目架构。

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) {
          // 改变状态
          item.title = title;
        }
      });
    },
  },
  watch: {
    // 简写版,没有深层监视,监测不了doList里面数据的变化,状态改变就用不了
    // value是最新的值
    /* doList(value) {
      localStorage.setItem("doList", JSON.stringify(value));
    }, */
    // 完整版
    doList: {
      // 开启深度监视
      deep: true,
      handler(value) {
        localStorage.setItem("doList", JSON.stringify(value));
      },
    },
  },
  // 绑定自定义事件,回调函数在当前这个组件,自动接收数据
  mounted() {
    // 改变状态
    this.$bus.$on("changeStatus", this.changeStatus);
    // this.$bus.$on("delItem", this.delItem);
    // 订阅消息:删除任务
    this.pubId = pubsub.subscribe("delItem", this.delItem);
    // 编辑任务
    this.$bus.$on("updateItem", this.updateTitle);
  },
  beforeDestroy() {
    // , "delItem"
    this.$bus.$off(["changeStatus"]);
    pubsub.unsubscribe(this.pubId);
  },
};
</script>
<style >
/* 这里面的样式是所有组件共用的 */
body {
  background: #fff;
}
.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0px, 1px, 2px,
    rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}
.btn-edit {
  background: green;
  border: 1px solid green;
  color: #fff;
  margin-right: 10px;
}
.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}
.btn:focus {
  outline: none;
}
.todo-container {
  width: 600px;
  margin: 0 auto;
  overflow: hidden;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>>

SearchHeader.vue

<template>
  <div class="todo-header">
    <input
      type="text"
      placeholder="请输入你的任务名称,按回车键确认"
      @keyup.enter="addItems"
      v-model="title"
    />
    <span v-if="flag" class="showtips">*内容不能为空</span>
  </div>
</template>

<script>
// nanoid:获取唯一的标识,是uuid的变种,轻量级的uuid
import { nanoid } from "nanoid";
export default {
  name: "SearchHeader",
  data() {
    return {
      title: "",
      flag: false,
    };
  },
  // 接收父组件传递来的数据(函数)
  // props: ["addItem"],
  methods: {
    addItems() {
      // 效验数据
      // this.title.trim()
      if (!this.title.trim()) {
        this.flag = true;
        this.title = "";
        return;
      }
      this.flag = false;
      // 将用户的输入包装成一个对象
      // console.log(e.target.value);
      const obj = {
        id: nanoid(),
        title: this.title.trim(),
        done: false,
      };
      // console.log(obj);
      // 调用该函数,将添加的对象作为参数
      // this.addItem(obj);
      // 触发组件自定义事件
      this.$emit("addItem", obj);
      // 清空输入框的内容
      this.title = "";
    },
  },
};
</script>
<style scoped>
.todo-header input {
  width: 560px;
  height: 28px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 7px;
}
.todo-header input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0px, 0x, 8px,
    rgba(82, 168, 236, 0.6);
}
.showtips {
  font-size: 10px;
  color: red;
}
</style>

SearchList.vue

<template>
  <ul class="todo-main">
    <transition-group appear name="item">
      <!-- 通过props属性,父子组件传值,将item传递给子组件 -->
      <SearchItem v-for="item in dataList" :key="item.id" :items="item" />
      <!-- :changeStatus="changeStatus"
        :delItem="delItem" -->
    </transition-group>
  </ul>
</template>

<script>
import SearchItem from "./SearchItem.vue";

export default {
  name: "SearchList",
  components: {
    SearchItem,
  },
  // , "changeStatus", "delItem"
  props: ["dataList"],
};
</script>

<style scoped>
.todo-main {
  margin-left: 0;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding-left: 0;
  margin-top: 10px;
  overflow: hidden;
}
.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
.item-enter-active {
  animation: showTime 1s linear;
}
.item-leave-active {
  animation: showTime 1s linear reverse;
}

@keyframes showTime {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0px);
  }
}
</style>

SearchItem.vue

<template>
  <!-- <transition name="item" appear> -->
  <li>
    <label for="">
      <!--方式一: @click="handler(items.id)" -->
      <input
        type="checkbox"
        :checked="items.done"
        @change="handler(items.id)"
      />
      <!-- 以下代码也能实现修改状态的功能,但是不建议用,因为有点违反原则,因为修改了props -->
      <!-- <input type="checkbox" v-model="items.done" /> -->
      <span v-show="!items.isEdit">{{ items.title }}</span>
      <!-- blur失去焦点时触发 -->
      <input
        ref="inpTitle"
        type="text"
        :value="items.title"
        v-show="items.isEdit"
        @keyup.enter="handleEdit(items, $event)"
      />
    </label>
    <button class="btn btn-danger" @click="handleDel(items.id)">删除</button>
    <button
      class="btn btn-edit"
      @click="showEdit(items)"
      v-show="!items.isEdit"
    >
      编辑
    </button>
  </li>
  <!-- </transition> -->
</template>

<script>
// 订阅与发布相关插件
import pubsub from "pubsub-js";
export default {
  name: "SearchItem",
  data() {
    return {};
  },
  // 声明接收items对象
  // , "changeStatus", "delItem"
  props: ["items"],
  methods: {
    // 修改单个任务状态
    handler(id) {
      // console.log(id);
      // 将doList中对应的任务的状态改变
      // this.changeStatus(id);
      this.$bus.$emit("changeStatus", id);
    },
    // 删除单个任务
    handleDel(id) {
      // console.log(id);
      if (confirm("确定删除该任务吗?")) {
        // 原生props方式:delItem是父组件传递过来的函数名
        // this.delItem(id);
        // 事件总线
        // delItem是自定义事件的事件名
        // this.$bus.$emit("delItem", id);
        // 消息与订阅
        // 发布消息
        // delItem是订阅消息的消息名
        pubsub.publish("delItem", id);
      } else {
        return;
      }
    },
    // 显示输入框
    showEdit(item) {
      // 判断item的isEdit属性是否存在,如果不存在就添加,如果存在了,就是直接改变其属性值
      // item.hasOwnProperty("isEdit")这个不行
      if (Object.prototype.hasOwnProperty.call(item, "isEdit")) {
        item.isEdit = true;
      } else {
        // item中isEdit的属性不存在,所以是undefined
        // item.isEdit = true;
        this.$set(item, "isEdit", true);
      }
      // vue是先将整个showEdit函数代码执行完才去解析页面,所以在执行focus()时,页面还没解析,所以无效
      // this.$refs.inpTitle.focus();
      // $nextTick的回调函数在DOM更新完毕之后才会调用执行
      this.$nextTick(function () {
        this.$refs.inpTitle.focus();
      });
    },
    // 任务编辑(回车之后)
    handleEdit(item, e) {
      item.isEdit = false;
      if (!e.target.value.trim()) {
        alert("任务名不能为空");
        return;
      }
      // 触发updateItem事件,发送数据
      this.$bus.$emit("updateItem", item.id, e.target.value);
    },
  },
};
</script>

<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}
li label {
  float: left;
  cursor: pointer;
}
li label input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}
li button {
  float: right;
  display: none;
  margin-top: 3px;
}
li:hover {
  background: #ddd;
}
li:hover button {
  display: block;
}
li:before {
  content: initials;
}
li:last-child {
  border-bottom: none;
}
/* 增删的动画效果 */
/* .item-enter-active {
  animation: showTime 1s linear;
}
.item-leave-active {
  animation: showTime 1s linear reverse;
}

@keyframes showTime {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0px);
  }
} */
</style>

SearchFooter.vue

<template>
  <div class="todo-footer">
    <label>
      <!-- 这个做法就需要用到dom元素 -->
      <!-- <input type="checkbox" :checked="isAll" @change="checkAll" /> -->
      <!-- checkbox的value值就是:true/false,双向绑定的做法用不到dom元素 -->
      <input type="checkbox" v-model="isAll" />
    </label>
    <span>已完成{{ doneTotal }} / 全部 {{ total }}</span>
    <button class="btn btn-danger" @click="handleDone">清除已完成任务</button>
  </div>
</template>

<script>
export default {
  name: "SearchFooter",
  props: ["doList"],
  data() {
    return {};
  },
  methods: {
    // 全选全不选效果
    // 用函数的做法会使用到dom元素
    /* checkAll(e) {
      this.checkedStatus(e.target.checked);
    }, */
    // 清除已完成的任务
    handleDone() {
      // this.delDone();
      this.$emit("delDone");
    },
  },
  computed: {
    // 已完成任务
    doneTotal() {
      /* let i = 0;
      // 遍历doList,
      this.doList.forEach((v) => {
        // 判断
        if (v.done) {
          i++;
        }
      });
      return i; */
      // reduce:累加器效果,数组有多长,就累加多少次
      // x 为reduce最后一个累加器之后的结果
      /* const x = this.doList.reduce((pre, current) => {
        return pre + (current.done ? 1 : 0);
      });
      return x; */
      return this.doList.reduce((pre, item) => {
        return pre + (item.done ? 1 : 0);
      }, 0);
    },
    // 总任务数
    total() {
      return this.doList.length;
    },
    // 全选
    /* isAll() {
      return this.doneTotal == this.total && this.total && this.total > 0;
    }, */
    // 原生双向绑定,这里就用不到dom元素
    isAll: {
      get() {
        return this.doneTotal == this.total && this.total && this.total > 0;
      },
      // 这里的value就是checkbox的结果:true/false
      set(value) {
        // this.checkedStatus(value);
        // 触发组件自定义事件
        this.$emit("checkedStatus", value);
      },
    },
  },
};
</script>

<style scoped>
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}
.todo-footer label {
  display: inline-block;
  margin-right: 28px;
  cursor: pointer;
}
.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}
.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值