欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue為什么要謹(jǐn)慎使用$attrs與$listeners

 更新時(shí)間:2020年08月27日 09:43:26   作者:眼已望穿  
這篇文章主要介紹了Vue為什么要謹(jǐn)慎使用$attrs與$listeners,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

Vue 開發(fā)過程中,如遇到祖先組件需要傳值到孫子組件時(shí),需要在兒子組件接收 props ,然后再傳遞給孫子組件,通過使用 v-bind="$attrs" 則會(huì)帶來極大的便利,但同時(shí)也會(huì)有一些隱患在其中。

隱患

先來看一個(gè)例子:

父組件:

{
 template: `
 <div>
 <input 
 type="text"
 v-model="input"
 placeholder="please input">
 <test :test="test" />
 </div>
 `,
 data() {
 return {
 input: '',
 test: '1111',
 };
 },
}

子組件:

{
 template: '<div v-bind="$attrs"></div>',
 updated() {
 console.log('Why should I update?');
 },
}

可以看到,當(dāng)我們在輸入框輸入值的時(shí)候,只有修改到 input 字段,從而更新父組件,而子組件的 props test 則是沒有修改的,按照 誰更新,更新誰 的標(biāo)準(zhǔn)來看,子組件是不應(yīng)該更新觸發(fā) updated 方法的,那這是為什么呢?

于是我發(fā)現(xiàn)這個(gè)“bug”,并迅速打開 gayhub 提了個(gè) issue ,想著我也是參與過重大開源項(xiàng)目的人了,還不免一陣竊喜。事實(shí)很殘酷,這么明顯的問題怎么可能還沒被發(fā)現(xiàn)...

無情……,于是我打開看了看,尤大說了這么一番話我就好像明白了:

那既然不是“bug”,那來看看是為什么吧。

前因

首先介紹一個(gè)前提,就是 Vue 在更新組件的時(shí)候是更新對應(yīng)的 dataprops 觸發(fā) Watcher 通知來更新渲染的。

每一個(gè)組件都有一個(gè)唯一對應(yīng)的 Watcher ,所以在子組件上的 props 沒有更新的時(shí)候,是不會(huì)觸發(fā)子組件的更新的。當(dāng)我們?nèi)サ糇咏M件上的 v-bind="$attrs" 時(shí)可以發(fā)現(xiàn), updated 鉤子不會(huì)再執(zhí)行,所以可以發(fā)現(xiàn)問題就出現(xiàn)在這里。

原因分析

Vue 源碼中搜索 $attrs ,找到 src/core/instance/render.js 文件:

export function initRender (vm: Component) {
 // ...
 defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
 defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
}

噢,amazing!就是它。可以看到在 initRender 方法中,將 $attrs 屬性綁定到了 this 上,并且設(shè)置成響應(yīng)式對象,離發(fā)現(xiàn)奧秘又近了一步。

依賴收集

我們知道 Vue 會(huì)通過 Object.defineProperty 方法來進(jìn)行依賴收集,由于這部分內(nèi)容也比較多,這里只進(jìn)行一個(gè)簡單了解。

 Object.defineProperty(obj, key, {
 get: function reactiveGetter () {
 const value = getter ? getter.call(obj) : val
 if (Dep.target) {
 dep.depend() // 依賴收集 -- Dep.target.addDep(dep)
 if (childOb) {
  childOb.dep.depend()
  if (Array.isArray(value)) {
  dependArray(value)
  }
 }
 }
 return value
 }
 })

通過對 get 的劫持,使得我們在訪問 $attrs 時(shí)它( dep )會(huì)將 $attrs 所在的 Watcher 收集到 depsubs 里面,從而在設(shè)置時(shí)進(jìn)行派發(fā)更新( notify() ),通知視圖渲染。

派發(fā)更新

下面是在改變響應(yīng)式數(shù)據(jù)時(shí)派發(fā)更新的核心邏輯:

 Object.defineProperty(obj, key, {
 set: function reactiveSetter (newVal) {
  const value = getter ? getter.call(obj) : val
  /* eslint-disable no-self-compare */
  if (newVal === value || (newVal !== newVal && value !== value)) {
  return
  }
  /* eslint-enable no-self-compare */
  if (process.env.NODE_ENV !== 'production' && customSetter) {
  customSetter()
  }
  if (setter) {
  setter.call(obj, newVal)
  } else {
  val = newVal
  }
  childOb = !shallow && observe(newVal)
  dep.notify()
 }
 })

很簡單的一部分代碼,就是在響應(yīng)式數(shù)據(jù)被 set 時(shí),調(diào)用 depnotify 方法,遍歷每一個(gè) Watcher 進(jìn)行更新。

 notify () {
 // stabilize the subscriber list first
 const subs = this.subs.slice()
 for (let i = 0, l = subs.length; i < l; i++) {
  subs[i].update()
 }
 }

了解到這些基礎(chǔ)后,我們再回頭看看 $attrs 是如何觸發(fā)子組件的 updated 方法的。

要知道子組件會(huì)被更新,肯定是在某個(gè)地方訪問到了 $attrs ,依賴被收集到 subs 里了,才會(huì)在派發(fā)時(shí)被通知需要更新。我們對比添加 v-bind="$attrs" 和不添加 v-bind="$attrs" 調(diào)試一下源碼可以看到:

 get: function reactiveGetter () {
 var value = getter ? getter.call(obj) : val;
 if (Dep.target) {
  dep.depend();
  if (childOb) {
  childOb.dep.depend();
  if (Array.isArray(value)) {
   dependArray(value);
  }
  }
 }
 var a = dep; // 看看當(dāng)前 dep 是啥
 debugger; // debugger 斷點(diǎn)
 return value
 }

當(dāng)綁定了 v-bind="$attrs" 時(shí),會(huì)多收集到一個(gè)依賴。

會(huì)有一個(gè) id8dep 里面收集了 $attrs 所在的 Watcher ,我們再對比一下有無 v-bind="$attrs" 時(shí)的 set

派發(fā)更新狀態(tài):

 set: function reactiveSetter (newVal) {
 var value = getter ? getter.call(obj) : val;
 /* eslint-disable no-self-compare */
 if (newVal === value || (newVal !== newVal && value !== value)) {
  return
 }
 /* eslint-enable no-self-compare */
 if (process.env.NODE_ENV !== 'production' && customSetter) {
  customSetter();
 }
 if (setter) {
  setter.call(obj, newVal);
 } else {
  val = newVal;
 }
 childOb = !shallow && observe(newVal);
 var a = dep; // 查看當(dāng)前 dep
 debugger; // debugger 斷點(diǎn)
 dep.notify();
 }

這里可以明顯看到也是 id8dep 正準(zhǔn)備遍歷 subs 通知 Watcher 來更新,也能看到 newValvalue

其實(shí)值并沒有改變而進(jìn)行了更新這個(gè)問題。

問題:$attrs 的依賴是如何被收集的呢?

我們知道依賴收集是在 get 中完成的,但是我們初始化的時(shí)候并沒有訪問數(shù)據(jù),那這是怎么實(shí)現(xiàn)的呢?

答案就在 vm._render() 這個(gè)方法會(huì)生成 Vnode 并在這個(gè)過程中會(huì)訪問到數(shù)據(jù),從而收集到了依賴。

那還是沒有解答出這個(gè)問題呀,別急,這還是一個(gè)鋪墊,因?yàn)槟阍?vm._render() 里也找不到在哪訪問到了 $attrs ...

柳暗花明

我們的代碼里和 vm._render() 都沒有對 $attrs 訪問,原因只可能出現(xiàn)在 v-bind 上了,我們使用 vue-template-compiler 對模板進(jìn)行編譯看看:

const compiler = require('vue-template-compiler');

const result = compiler.compile(
 // `
 // <div :test="test">
 //  <p>測試內(nèi)容</p>
 // </div>
 // `
 `
 <div v-bind="$attrs">
 <p>測試內(nèi)容</p>
 </div>
`
);

console.log(result.render);

// with (this) {
// return _c(
//  'div',
//  { attrs: { test: test } },
//  [
//  _c('p', [_v('測試內(nèi)容')])
//  ]
// );
// }

// with (this) {
// return _c(
//  'div',
//  _b({}, 'div', $attrs, false),
//  [
//  _c('p', [_v('測試內(nèi)容')])
//  ]
// );
// }

這就是最終訪問 $attrs 的地方了,所以 $attrs 會(huì)被收集到依賴中,當(dāng) inputv-model 的值更新時(shí),觸發(fā) set 通知更新,而在更新組件時(shí)調(diào)用的 updateChildComponent 方法中會(huì)對 $attrs 進(jìn)行賦值:

 // update $attrs and $listeners hash
 // these are also reactive so they may trigger child update if the child
 // used them during render
 vm.$attrs = parentVnode.data.attrs || emptyObject;
 vm.$listeners = listeners || emptyObject;

所以會(huì)觸發(fā) $attrsset ,導(dǎo)致它所在的 Watcher 進(jìn)行更新,也就會(huì)導(dǎo)致子組件更新了。而如果沒有綁定 v-bind="$attrs" ,則雖然也會(huì)到這一步,但是沒有依賴收集的過程,就無法去更新子組件了。

奇淫技巧

如果又想圖人家身子,啊呸,圖人家方便,又想要好點(diǎn)的性能怎么辦呢?這里有一個(gè)曲線救國的方法:

<template>
 <Child v-bind="attrsCopy" />
</template>

<script>
import _ from 'lodash';
import Child from './Child';

export default {
 name: 'Child',
 components: {
 Child,
 },
 data() {
 return {
  attrsCopy: {},
 };
 },
 watch: {
 $attrs: {
  handler(newVal, value) {
  if (!_.isEqual(newVal, value)) {
   this.attrsCopy = _.cloneDeep(newVal);
  }
  },
  immediate: true,
 },
 },
};
</script>

總結(jié)

到此為止,我們就已經(jīng)分析完了 $attrs 數(shù)據(jù)沒有變化,卻讓子組件更新的原因,源碼中有這樣一段話:

// $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated

一開始這樣設(shè)計(jì)目的是為了 HOC 高階組件更好的創(chuàng)建使用,便于 HOC 組件總能對數(shù)據(jù)變化做出反應(yīng),但是在實(shí)際過程中與 v-model 產(chǎn)生了一些副作用,對于這兩者的使用,建議在沒有數(shù)據(jù)頻繁變化時(shí)可以使用,或者使用上面的奇淫技巧,以及……把產(chǎn)生頻繁變化的部分扔到一個(gè)單獨(dú)的組件中讓他自己自娛自樂去吧。

到此這篇關(guān)于Vue為什么要謹(jǐn)慎使用$attrs與$listeners的文章就介紹到這了,更多相關(guān)Vue $attrs與$listeners內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論