【问题标题】:Intersection Observer doesn't observe new elementsIntersection Observer 没有观察到新元素
【发布时间】:2020-12-11 11:38:30
【问题描述】:

我需要观察列表中的元素,并在它们出现在用户视口中时将它们标记为已读。但是当我在数组的开头添加新元素(unshift)时,观察者不起作用:(

我使用 Vue,但我知道问题与它无关。

这是观察者方法,它不会为新元素触发:

onElementObserved(entries) {
      entries.forEach(({ target, isIntersecting}) => {
          if (!isIntersecting) {
            return;
          }
          
          this.observer.unobserve(target);
        
          setTimeout(() => {
            const i = target.getAttribute("data-index");
            this.todos[i].seen = true;
          }, 1000)
      });
    }

codepen

【问题讨论】:

    标签: vue.js intersection-observer


    【解决方案1】:

    v-for 项没有指定key,因此 Vue 按索引跟踪每个列表元素。当一个新项目未移动到列表中时,新元素的索引为0,该索引已存在于列表中,因此现有元素只是简单地修补到位。由于没有创建新元素,因此不会触发 Intersection Observer。

    要解决此问题,请在 v-for 中为每个项目设置一个唯一的 key。例如,您可以为每个数组元素添加一个id 属性,然后将该id 绑定为<todo> 的键:

    let nextId = 0;?
    
    const TodoList = Vue.extend({
      template: `
        <div>
          <ul class="TodoList">
            <todo 
              v-for="(todo, i) in todos" 
              :todo="todo" 
              :observer="observer"
              :index="i"
              :key="todo.id"?
            ></todo>
          </ul>
          <button @click="pushNewTodo()">PUSH NEW</button>
        </div>
      `,
      data() {
        return {
          todos: [  ?
            { id: nextId++, seen: false, text: "Add app skeleton" },
            { id: nextId++, seen: false, text: "Add to-do component" },       
            { id: nextId++, seen: false, text: "Add to-do list component" },
            { id: nextId++, seen: false, text: "Style the components" },
            { id: nextId++, seen: false, text: "Add the IntersectionObserver" },
            { id: nextId++, seen: false, text: "Mark to-do's as seen" }
          ],
        };
      },
      methods: {
        pushNewTodo() {             ?
          this.todos.unshift({ id: nextId++, seen: false, text: "Add app skeleton BLAH BLAH BLAH" })
        },
      }
    })
    

    updated codepen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-04
      • 2016-03-29
      • 1970-01-01
      相关资源
      最近更新 更多