记 13 实战杂记

82 阅读2分钟

实战杂记

foreach 全选 + e.target 事件对象e

在事件处理程序中使用事件(如 click)时,通常会有一个事件对象 e 被自动传递给这个处理程序( 函数 )。这个事件对象包含了与事件相关的信息、属性和方法,有点击的位置( e.clientXe.clientY 可以告诉你点击发生时鼠标的坐标 )、被点击的元素(e.target)、事件的类型等。

    toggleAll(e) {
      this.todos.forEach(
        (todo) => {
          todo.completed = e.target.checked;
        }
      );
    },

监听事件时,传递函数的书写

window.addEventListener("hashchange", this.onHashChange);

window.addEventListener("hashchange", fun() ); 中存在一个常见的错误。fun() 是调用函数,而不是将 fun 函数本身传递给 addEventListener。这会导致 fun() 函数立即执行,并且其返回值(如果有的话)被作为事件处理函数。如果你的 fun 函数没有返回一个函数,那么当 hashchange 事件触发时,实际上没有任何函数被调用。

正确的方式是将 fun 函数作为一个引用传递给 addEventListener,而不是调用它。这样,当事件触发时,fun 函数才会被执行。

正则替换

      // replace(//, '') 将//里的内容替换为空
      // 去除#/  /是正则标识,需要在前添加转义字符\,以正确匹配
      // ?表示匹配0次或1次  +表示匹配1次或多次  *表示匹配0次或多次
      const hash = window.location.hash.replace(/#\/?/, "");

splice + indexOf

// 找到要删除的todo的索引,然后使用splice方法删除
this.todos.splice(this.todos.indexOf(todo), 1);

过滤filter 包含 includes

// 过滤/删除掉已完成的todo
this.todos = this.todos.filter((todo) => !todo.completed);

//查询是否包含相应内容
if (["all", "active", "completed"].includes(hash)) 

判断中0的省略

v-show="todos.length" 

条件语句 + 模板字符串

 {{ remain === 1 ? "item" : "items"}}

switch case

      switch (this.visibility) {
        case "all":
          return this.todos;
        case "active":
          return this.todos.filter((todo) => !todo.completed);
        case "completed":
          return this.todos.filter((todo) => todo.completed);
      }

元素挂载后开始监听 + this.$nextTick 在重新渲染后回调

this.$nextTick(()=>{})

操作不能写在生命周期里,应该用单独的methods操作 钩子函数中的监听事件应设置主动触发,避免刷新后失效

mounted() {
    window.addEventListener("hashchange", this.onHashChange);
    this.onHashChange(); //刷新时也需要执行一次
  },

v-for + ref

//在v-for的元素上,结合list中关联值进行特定ref元素的绑定
:ref="'input' + todo.id"

//在$nextTick 中,使用this.$refs[`input${todo.id}`]进行取值及相关修改
this.$nextTick(() => {
        const input = this.$refs[`input${todo.id}`];
        if (input) {
          input[0].focus();
        }
      });