---
# System prepended metadata

title: '【js筆記】[Browser API] MutationObserver, IntersectionObserver'
tags: [JAVASCRIPT]

---

---
tags: JAVASCRIPT
---
【js筆記】[Browser API] MutationObserver, IntersectionObserver
===
[參考](https://ithelp.ithome.com.tw/articles/10217810)

## observer 清除
```javascript=
unobserve：停止观察一个元素
disconnect：停止观察所有元素
```
```javascript=
export default {
    destroyed() {
        this.observer.disconnect()
    }
    // ...
}
```
## MutationObserver
- MutationObserver 可以監聽 DOM 的變化
- 如果不用的話要呼叫 disconnect 這個方法來停止監聽。
- vue 透過MutationObserver 的方式來實作 nextTick
```javascript
const mo = new MutationObserver((mutations) => {
  mutations.forEach(mutation => {
		// your code
  })
});

mo.observe(target);

// 不用之後
mo.disconnect()
```

## IntersectionObserver
scroll效能差
- 用來確認在 target 是否有進入當前的 viewport
- 實作頁面無限滾動
- 實作 Lazy loading
- new IntersectionObserver(callback, options);
```javascript=
const io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // do fetching
    }
  });
}, {
  root
  thresholds
});

io.observe(target);
```
### 無限捲動
原文: [https://www.w3cplus.com/vue/build-an-infinite-scroll-component-using-intersection-observer-api.html](https://www.w3cplus.com/vue/build-an-infinite-scroll-component-using-intersection-observer-api.html)
```htmlmixed=
<template lang="pug">
  .news
    h1 news
    hr
    .news__list
      ul
          li.news__list__item.d-block.mb-3(v-for="item in items")
            .d-block.font-weight-bold {{ item.id }} {{ item.name }}
            .d-block {{ item.body}}
          Observer(@intersect="intersected")

</template>

<script>

import Observer from '@/components/Observer'

export default {
  name: 'news',
  components: {
    Observer
  },
  data () {
    return {
      page: 1,
      items: []
    }
  },
  methods: {
    async intersected () {
      const res = await fetch(`https://jsonplaceholder.typicode.com/comments?&_page=${this.page}&_limit=12`)
      this.page++
      const items = await res.json()
      this.items = [...this.items, ...items]
    }
  }
}

</script>

```