阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Vue.js 中 Computed 的特点

      问题

      VueComputed的特点

      答案

      • 默认computed也是一个watcher是具备缓存的,只要当依赖的属性发生变化时才会更新视图

      https://a.axihe.com/focus/vue/06.jpg

      对应源码

      function initComputed (vm: Component, computed: Object) {
        const watchers = vm._computedWatchers = Object.create(null)
        const isSSR = isServerRendering()
        for (const key in computed) {
          const userDef = computed[key]
          const getter = typeof userDef === 'function' ? userDef : userDef.get
          if (!isSSR) {
            // create internal watcher for the computed property.
            watchers[key] = new Watcher(
              vm,
              getter || noop,
              noop,
              computedWatcherOptions
            )
          }
      
          // component-defined computed properties are already defined on the
          // component prototype. We only need to define computed properties defined
          // at instantiation here.
          if (!(key in vm)) {
            defineComputed(vm, key, userDef)
          } else if (process.env.NODE_ENV !== 'production') {
            if (key in vm.$data) {
              warn(`The computed property "${key}" is already defined in data.`, vm)
            } else if (vm.$options.props && key in vm.$options.props) {
              warn(`The computed property "${key}" is already defined as a prop.`, vm)
            }
          }
        }
      }
      function createComputedGetter (key) {
        return function computedGetter () {
          const watcher = this._computedWatchers && this._computedWatchers[key]
          if (watcher) {
            if (watcher.dirty) { // 如果依赖的值没发生变化,就不会重新求值
              watcher.evaluate()
            }
            if (Dep.target) {
              watcher.depend()
            }
            return watcher.value
          }
        }
      }
      

      更多面试题

      如果你想了解更多的前端面试题,可以查看本站的WEB前端面试题 ,这里基本包涵了市场上的所有前端方面的面试题,也有一些大公司的面试图,可以让你面试更加顺利。

      面试题
      HTMLCSSJavaScript
      jQueryVue.jsReact
      算法HTTPBabel
      BootStrapElectronGulp
      Node.js前端经验相关前端综合
      Webpack微信小程序-

      这些题库还在更新中,如果你有不错的面试题库欢迎分享给我,我整理后放上来;人人为我,我为人人,互帮互助,共同提高,祝大家都拿到心仪的Offer!

      目录
      目录