服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue为什么要谨慎使用$attrs与$listeners

Vue为什么要谨慎使用$attrs与$listeners

2021-09-01 16:00眼已望穿 JavaScript

这篇文章主要介绍了Vue为什么要谨慎使用$attrs与$listeners,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

Vue 开发过程中,如遇到祖先组件需要传值到孙子组件时,需要在儿子组件接收 props ,然后再传递给孙子组件,通过使用 v-bind="$attrs" 则会带来极大的便利,但同时也会有一些隐患在其中。

隐患

先来看一个例子:

Vue为什么要谨慎使用$attrs与$listeners

父组件:

  1. {
  2. template: `
  3. <div>
  4. <input
  5. type="text"
  6. v-model="input"
  7. placeholder="please input">
  8. <test :test="test" />
  9. </div>
  10. `,
  11. data() {
  12. return {
  13. input: '',
  14. test: '1111',
  15. };
  16. },
  17. }

子组件:

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

可以看到,当我们在输入框输入值的时候,只有修改到 input 字段,从而更新父组件,而子组件的 props test 则是没有修改的,按照 谁更新,更新谁 的标准来看,子组件是不应该更新触发 updated 方法的,那这是为什么呢?

于是我发现这个“bug”,并迅速打开 gayhub 提了个 issue ,想着我也是参与过重大开源项目的人了,还不免一阵窃喜。事实很残酷,这么明显的问题怎么可能还没被发现...

Vue为什么要谨慎使用$attrs与$listeners

无情……,于是我打开看了看,尤大说了这么一番话我就好像明白了:

Vue为什么要谨慎使用$attrs与$listeners

那既然不是“bug”,那来看看是为什么吧。

前因

首先介绍一个前提,就是 Vue 在更新组件的时候是更新对应的 dataprops 触发 Watcher 通知来更新渲染的。

每一个组件都有一个唯一对应的 Watcher ,所以在子组件上的 props 没有更新的时候,是不会触发子组件的更新的。当我们去掉子组件上的 v-bind="$attrs" 时可以发现, updated 钩子不会再执行,所以可以发现问题就出现在这里。

原因分析

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

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

噢,amazing!就是它。可以看到在 initRender 方法中,将 $attrs 属性绑定到了 this 上,并且设置成响应式对象,离发现奥秘又近了一步。

依赖收集

我们知道 Vue 会通过 Object.defineProperty 方法来进行依赖收集,由于这部分内容也比较多,这里只进行一个简单了解。

  1. Object.defineProperty(obj, key, {
  2. get: function reactiveGetter () {
  3. const value = getter ? getter.call(obj) : val
  4. if (Dep.target) {
  5. dep.depend() // 依赖收集 -- Dep.target.addDep(dep)
  6. if (childOb) {
  7. childOb.dep.depend()
  8. if (Array.isArray(value)) {
  9. dependArray(value)
  10. }
  11. }
  12. }
  13. return value
  14. }
  15. })

通过对 get 的劫持,使得我们在访问 $attrs 时它( dep )会将 $attrs 所在的 Watcher 收集到 depsubs 里面,从而在设置时进行派发更新( notify() ),通知视图渲染。

派发更新

下面是在改变响应式数据时派发更新的核心逻辑:

  1. Object.defineProperty(obj, key, {
  2. set: function reactiveSetter (newVal) {
  3. const value = getter ? getter.call(obj) : val
  4. /* eslint-disable no-self-compare */
  5. if (newVal === value || (newVal !== newVal && value !== value)) {
  6. return
  7. }
  8. /* eslint-enable no-self-compare */
  9. if (process.env.NODE_ENV !== 'production' && customSetter) {
  10. customSetter()
  11. }
  12. if (setter) {
  13. setter.call(obj, newVal)
  14. } else {
  15. val = newVal
  16. }
  17. childOb = !shallow && observe(newVal)
  18. dep.notify()
  19. }
  20. })

很简单的一部分代码,就是在响应式数据被 set 时,调用 depnotify 方法,遍历每一个 Watcher 进行更新。

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

了解到这些基础后,我们再回头看看 $attrs 是如何触发子组件的 updated 方法的。

要知道子组件会被更新,肯定是在某个地方访问到了 $attrs ,依赖被收集到 subs 里了,才会在派发时被通知需要更新。我们对比添加 v-bind="$attrs" 和不添加 v-bind="$attrs" 调试一下源码可以看到:

  1. get: function reactiveGetter () {
  2. var value = getter ? getter.call(obj) : val;
  3. if (Dep.target) {
  4. dep.depend();
  5. if (childOb) {
  6. childOb.dep.depend();
  7. if (Array.isArray(value)) {
  8. dependArray(value);
  9. }
  10. }
  11. }
  12. var a = dep; // 看看当前 dep 是啥
  13. debugger; // debugger 断点
  14. return value
  15. }

当绑定了 v-bind="$attrs" 时,会多收集到一个依赖。

Vue为什么要谨慎使用$attrs与$listeners

会有一个 id8dep 里面收集了 $attrs 所在的 Watcher ,我们再对比一下有无 v-bind="$attrs" 时的 set

派发更新状态:

  1. set: function reactiveSetter (newVal) {
  2. var value = getter ? getter.call(obj) : val;
  3. /* eslint-disable no-self-compare */
  4. if (newVal === value || (newVal !== newVal && value !== value)) {
  5. return
  6. }
  7. /* eslint-enable no-self-compare */
  8. if (process.env.NODE_ENV !== 'production' && customSetter) {
  9. customSetter();
  10. }
  11. if (setter) {
  12. setter.call(obj, newVal);
  13. } else {
  14. val = newVal;
  15. }
  16. childOb = !shallow && observe(newVal);
  17. var a = dep; // 查看当前 dep
  18. debugger; // debugger 断点
  19. dep.notify();
  20. }

Vue为什么要谨慎使用$attrs与$listeners

这里可以明显看到也是 id8dep 正准备遍历 subs 通知 Watcher 来更新,也能看到 newValvalue

其实值并没有改变而进行了更新这个问题。

问题:$attrs 的依赖是如何被收集的呢?

我们知道依赖收集是在 get 中完成的,但是我们初始化的时候并没有访问数据,那这是怎么实现的呢?

答案就在 vm._render() 这个方法会生成 Vnode 并在这个过程中会访问到数据,从而收集到了依赖。

那还是没有解答出这个问题呀,别急,这还是一个铺垫,因为你在 vm._render() 里也找不到在哪访问到了 $attrs ...

柳暗花明

我们的代码里和 vm._render() 都没有对 $attrs 访问,原因只可能出现在 v-bind 上了,我们使用 vue-template-compiler 对模板进行编译看看:

  1. const compiler = require('vue-template-compiler');
  2.  
  3. const result = compiler.compile(
  4. // `
  5. // <div :test="test">
  6. // <p>测试内容</p>
  7. // </div>
  8. // `
  9. `
  10. <div v-bind="$attrs">
  11. <p>测试内容</p>
  12. </div>
  13. `
  14. );
  15.  
  16. console.log(result.render);
  17.  
  18. // with (this) {
  19. // return _c(
  20. // 'div',
  21. // { attrs: { test: test } },
  22. // [
  23. // _c('p', [_v('测试内容')])
  24. // ]
  25. // );
  26. // }
  27.  
  28. // with (this) {
  29. // return _c(
  30. // 'div',
  31. // _b({}, 'div', $attrs, false),
  32. // [
  33. // _c('p', [_v('测试内容')])
  34. // ]
  35. // );
  36. // }

这就是最终访问 $attrs 的地方了,所以 $attrs 会被收集到依赖中,当 inputv-model 的值更新时,触发 set 通知更新,而在更新组件时调用的 updateChildComponent 方法中会对 $attrs 进行赋值:

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

所以会触发 $attrsset ,导致它所在的 Watcher 进行更新,也就会导致子组件更新了。而如果没有绑定 v-bind="$attrs" ,则虽然也会到这一步,但是没有依赖收集的过程,就无法去更新子组件了。

奇淫技巧

如果又想图人家身子,啊呸,图人家方便,又想要好点的性能怎么办呢?这里有一个曲线救国的方法:

  1. <template>
  2. <Child v-bind="attrsCopy" />
  3. </template>
  4.  
  5. <script>
  6. import _ from 'lodash';
  7. import Child from './Child';
  8.  
  9. export default {
  10. name: 'Child',
  11. components: {
  12. Child,
  13. },
  14. data() {
  15. return {
  16. attrsCopy: {},
  17. };
  18. },
  19. watch: {
  20. $attrs: {
  21. handler(newVal, value) {
  22. if (!_.isEqual(newVal, value)) {
  23. this.attrsCopy = _.cloneDeep(newVal);
  24. }
  25. },
  26. immediate: true,
  27. },
  28. },
  29. };
  30. </script>

总结

到此为止,我们就已经分析完了 $attrs 数据没有变化,却让子组件更新的原因,源码中有这样一段话:

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

一开始这样设计目的是为了 HOC 高阶组件更好的创建使用,便于 HOC 组件总能对数据变化做出反应,但是在实际过程中与 v-model 产生了一些副作用,对于这两者的使用,建议在没有数据频繁变化时可以使用,或者使用上面的奇淫技巧,以及……把产生频繁变化的部分扔到一个单独的组件中让他自己自娱自乐去吧。

到此这篇关于Vue为什么要谨慎使用$attrs与$listeners的文章就介绍到这了,更多相关Vue $attrs与$listeners内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.im/post/6864858225443864583

延伸 · 阅读

精彩推荐