vue2 全局事件总线

<template>
  <div id="container">
    <div id="parent">
      <TodoHeader @addTodo="addTodo" />
      <TodoList :todos="todos" :removeTodo="deleteTodo" />
      <TodoFooter
        :finish="finish"
        :all="all"
        :clear="clear"
        :doneAll="doneAll"
      />
    </div>
  </div>
</template>

<script>
import TodoFooter from "./TodoFooter.vue";
import TodoHeader from "./TodoHeader.vue";
import TodoList from "./TodoList.vue";

export default {
  name: "TodoComponent",
  components: {
    TodoFooter,
    TodoHeader,
    TodoList,
  },
  data() {
    return {
      todos: [],
    };
  },
  mounted() {
    let arr = JSON.parse(localStorage.getItem("todos"));

    if (arr === null) {
      arr = [];
    }
    this.todos = arr;


    //放入全局事件总线
    this.$bus.$on('removeTodo',this.deleteTodo);
  },
  beforeDestroy(){
      this.$bus.$off('removeTodo');
  },
  methods: {
    addTodo(x) {
      console.log("我是Todo组件,我收到了数据", x);
      this.todos.unshift(x);
    },
    clear() {
      console.log("清除了");

      const idList = this.todos.filter((x) => x.done).map((x) => x.id);

      for (let i = 0; i < this.todos.length; i++) {
        if (idList.includes(this.todos[i].id)) {
          this.todos.splice(i, 1);
          i--;
        }
      }

      console.log(this.todos);
    },
    doneAll(choose) {
      this.todos.forEach((x) => (x.done = choose));
    },

    deleteTodo(id) {
      for (var i = 0; i < this.todos.length; i++) {
        if (this.todos[i].id === id) {
          console.log(i, "下标");

          break;
        }
      }

      this.todos.splice(i, 1);
    },
  },
  computed: {
    finish() {
      return this.todos.filter((x) => x.done).length;
    },
    all() {
      return this.todos.length;
    },
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem("todos", JSON.stringify(value));
      }
    }
  }
};
</script>

<style scoped>
#parent {
  width: 600px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center; /*  水平居左 */
  align-items: center; /* 垂直居中 */
  flex-direction: column; /* 垂直排列子元素 */
}
#parent > * {
  margin: 10px 0px;
}
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值