Vue為什么要謹(jǐn)慎使用$attrs與$listeners
前言
在 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í)候是更新對(duì)應(yīng)的 data 和 props 觸發(fā) Watcher 通知來更新渲染的。
每一個(gè)組件都有一個(gè)唯一對(duì)應(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)式對(duì)象,離發(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
}
})
通過對(duì) get 的劫持,使得我們在訪問 $attrs 時(shí)它( dep )會(huì)將 $attrs 所在的 Watcher 收集到 dep 的 subs 里面,從而在設(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)用 dep 的 notify 方法,遍歷每一個(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í)被通知需要更新。我們對(duì)比添加 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è) id 為 8 的 dep 里面收集了 $attrs 所在的 Watcher ,我們再對(duì)比一下有無 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();
}

這里可以明顯看到也是 id 為 8 的 dep 正準(zhǔn)備遍歷 subs 通知 Watcher 來更新,也能看到 newVal 與 value
其實(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() 都沒有對(duì) $attrs 訪問,原因只可能出現(xiàn)在 v-bind 上了,我們使用 vue-template-compiler 對(duì)模板進(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) input 中 v-model 的值更新時(shí),觸發(fā) set 通知更新,而在更新組件時(shí)調(diào)用的 updateChildComponent 方法中會(huì)對(duì) $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ā) $attrs 的 set ,導(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 組件總能對(duì)數(shù)據(jù)變化做出反應(yīng),但是在實(shí)際過程中與 v-model 產(chǎn)生了一些副作用,對(duì)于這兩者的使用,建議在沒有數(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)文章
Element-ui設(shè)置el-table表頭全選框隱藏或禁用
這篇文章主要給大家介紹了關(guān)于Element-ui設(shè)置el-table表頭全選框隱藏或禁用的相關(guān)資料,文中手把手教你實(shí)現(xiàn)el-table實(shí)現(xiàn)跨表格禁用選項(xiàng),需要的朋友可以參考下2023-07-07
vue+echarts動(dòng)態(tài)更新數(shù)據(jù)及數(shù)據(jù)變化重新渲染方式
這篇文章主要介紹了vue+echarts動(dòng)態(tài)更新數(shù)據(jù)及數(shù)據(jù)變化重新渲染方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
vue3在自定義hooks中使用useRouter報(bào)錯(cuò)的解決方案
這篇文章主要介紹了vue3在自定義hooks中使用useRouter報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
Vue3?使用v-md-editor如何動(dòng)態(tài)上傳圖片的方法實(shí)現(xiàn)
本文主要介紹了Vue3?使用v-md-editor如何動(dòng)態(tài)上傳圖片,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
在Vue3中使用vue-qrcode庫實(shí)現(xiàn)二維碼生成的方法
在Vue3中實(shí)現(xiàn)二維碼生成需要使用第三方庫來處理生成二維碼的邏輯,常用的庫有 qrcode和 vue-qrcode,這篇文章主要介紹了在Vue3中使用vue-qrcode庫實(shí)現(xiàn)二維碼生成,需要的朋友可以參考下2023-12-12
vue cli 3.0下配置開發(fā)環(huán)境下的sourcemap問題
這篇文章主要介紹了vue cli 3.0下配置開發(fā)環(huán)境下的sourcemap問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
更強(qiáng)大的vue ssr實(shí)現(xiàn)預(yù)取數(shù)據(jù)的方式
這篇文章主要介紹了更強(qiáng)大的 vue ssr 預(yù)取數(shù)據(jù)的方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07

