资讯专栏INFORMATION COLUMN

JS每日一题: 请简述一下vuex实现原理

JohnLui / 1157人阅读

摘要:给的实例注入一个的属性,这也就是为什么我们在的组件中可以通过访问到的各种数据和状态源码位置,是怎么实现的源码位置是对的的初始化,它接受个参数,为当前实例,为的,为执行的回调函数,为当前模块的路径。

20190221

请简述一下vuex实现原理

对vuex基础概念有不懂的可以点这里

vuex实现原理我们简单过一遍源码 地址 https://github.com/vuejs/vuex

首先我们例出几个问题进行思考

store是怎么注册的?

mutation,commit 是怎么实现的?

辅助函数是怎么实现的?

store是怎么注册的

看了下面的源码就很清楚了, 我们看到vuex在vue 的生命周期中的初始化钩子前插入一段 Vuex 初始化代码。给 Vue 的实例注入一个 $store 的属性,这也就是为什么我们在 Vue 的组件中可以通过 this.$store.xxx 访问到 Vuex 的各种数据和状态

// 源码位置 https://github.com/vuejs/vuex/blob/665455f8daf8512e7adbf63c2842bc0b1e39efdb/src/mixin.js

export default function (Vue) {
  const version = Number(Vue.version.split(".")[0])

  if (version >= 2) {
    Vue.mixin({ beforeCreate: vuexInit })
  } else {
    // override init and inject vuex init procedure
    // for 1.x backwards compatibility.
    const _init = Vue.prototype._init
    Vue.prototype._init = function (options = {}) {
      options.init = options.init
        ? [vuexInit].concat(options.init)
        : vuexInit
      _init.call(this, options)
    }
  }

  /**
   * Vuex init hook, injected into each instances init hooks list.
   */

  function vuexInit () {
    const options = this.$options
    // store injection
    if (options.store) {
      this.$store = typeof options.store === "function"
        ? options.store()
        : options.store
    } else if (options.parent && options.parent.$store) {
      this.$store = options.parent.$store
    }
  }
}
mutations,commit 是怎么实现的
// 源码位置  https://github.com/vuejs/vuex/blob/665455f8daf8512e7adbf63c2842bc0b1e39efdb/src/store.js#L417
function registerMutation (store, type, handler, path = []) {
  const entry = store._mutations[type] || (store._mutations[type] = [])
  entry.push(function wrappedMutationHandler (payload) {
    handler(getNestedState(store.state, path), payload)
  })
}

registerMutation 是对 store 的 mutation 的初始化,它接受 4 个参数,store为当前 Store 实例,type为 mutation 的 key,handler 为 mutation 执行的回调函数,path 为当前模块的路径。mutation 的作用就是同步修改当前模块的 state ,函数首先通过 type 拿到对应的 mutation 对象数组, 然后把一个 mutation 的包装函数 push 到这个数组中,这个函数接收一个参数 payload,这个就是我们在定义 mutation 的时候接收的额外参数。这个函数执行的时候会调用 mutation 的回调函数,并通过 getNestedState(store.state, path) 方法得到当前模块的 state,和 playload 一起作为回调函数的参数

我们知道mutation是通过commit来触发的,这里我们也来看一下commit的定义

// 源码位置 https://github.com/vuejs/vuex/blob/665455f8daf8512e7adbf63c2842bc0b1e39efdb/src/store.js#L82

  commit (_type, _payload, _options) {
    // check object-style commit
    const {
      type,
      payload,
      options
    } = unifyObjectStyle(_type, _payload, _options)

    const mutation = { type, payload }
    const entry = this._mutations[type]
    if (!entry) {
      if (process.env.NODE_ENV !== "production") {
        console.error(`[vuex] unknown mutation type: ${type}`)
      }
      return
    }
    this._withCommit(() => {
      entry.forEach(function commitIterator (handler) {
        handler(payload)
      })
    })
    this._subscribers.forEach(sub => sub(mutation, this.state))

    if (
      process.env.NODE_ENV !== "production" &&
      options && options.silent
    ) {
      console.warn(
        `[vuex] mutation type: ${type}. Silent option has been removed. ` +
        "Use the filter functionality in the vue-devtools"
      )
    }
  }

commit 支持 3 个参数,type 表示 mutation 的类型,payload 表示额外的参数,根据 type 去查找对应的 mutation,如果找不到,则输出一条错误信息,否则遍历这个 type 对应的 mutation 对象数组,执行 handler(payload) 方法,这个方法就是之前定义的 wrappedMutationHandler(handler),执行它就相当于执行了 registerMutation 注册的回调函数

辅助函数

辅助函数的实现都差不太多,这里只讲解mapState

// 源码地址  https://github.com/vuejs/vuex/blob/665455f8daf8512e7adbf63c2842bc0b1e39efdb/src/helpers.js#L7

export const mapState = normalizeNamespace((namespace, states) => {
  const res = {}
  normalizeMap(states).forEach(({ key, val }) => {
    res[key] = function mappedState () {
      let state = this.$store.state
      let getters = this.$store.getters
      if (namespace) {
        const module = getModuleByNamespace(this.$store, "mapState", namespace)
        if (!module) {
          return
        }
        state = module.context.state
        getters = module.context.getters
      }
      return typeof val === "function"
        ? val.call(this, state, getters)
        : state[val]
    }
    // mark vuex getter for devtools
    res[key].vuex = true
  })
  return res
})

mapState在调用了 normalizeMap 函数后,把传入的 states 转换成由 {key, val} 对象构成的数组,接着调用 forEach 方法遍历这个数组,构造一个新的对象,这个新对象每个元素都返回一个新的函数 mappedState,函数对 val 的类型判断,如果 val 是一个函数,则直接调用这个 val 函数,把当前 store 上的 state 和 getters 作为参数,返回值作为 mappedState 的返回值;否则直接把 this.$store.state[val] 作为 mappedState 的返回值

为了更直观的理解,我们看下最终mapState的效果

  computed: mapState({
    name: state => state.name,
  })
  
  // 等同于
  
  computed: {
    name: this.$store.state.name
  }
关于JS每日一题

JS每日一题可以看成是一个语音答题社区
每天利用碎片时间采用60秒内的语音形式来完成当天的考题
群主在次日0点推送当天的参考答案

注 绝不仅限于完成当天任务,更多是查漏补缺,学习群内其它同学优秀的答题思路

点击加入答题

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/102015.html

相关文章

  • JS每日一题简述一下Vue.js的template编译过程?

    摘要:问简述一下的编译过程先上一张图大致看一下整个流程从上图中我们可以看到是从后开始进行中整体逻辑分为三个部分解析器将模板字符串转换成优化器对进行静态节点标记,主要用来做虚拟的渲染优化代码生成器使用生成函数代码字符串开始前先解释一下抽象 20190215问 简述一下Vue.js的template编译过程? 先上一张图大致看一下整个流程showImg(https://image-static....

    NicolasHe 评论0 收藏0
  • JS每日一题:什么情况下适合使合vuexVuex使用中有几个步骤?

    摘要:什么情况下适合使合使用中有几个步骤开始之前先简单了解一下定义是一个状态管理机制采用集中式存储应用所有组件的状态嗯,就是一句话能说明白的,没明白的,我们用代码再理解一下什么叫集中式式存储比如下面这段代码,同时需要用到,那么我们首先能想到就是在 20190121 什么情况下适合使合vuex?Vuex使用中有几个步骤? 开始之前先简单了解一下vuex 定义: vuex是一个状态管理机制,采用...

    wow_worktile 评论0 收藏0
  • 前端知识点(二)

    摘要:在给一个目标对象为构造函数的代理对象构造实例时触发该操作,比如在执行时。 1、元素上下垂直居中的方式有哪些? 元素水平垂直居中的方式有哪些? absolute加margin方案 fixed 加 margin 方案 display:table 方案 行内元素line-height方案 flex 弹性布局方案 transform 未知元素宽高解决方案 absolute加mar...

    zacklee 评论0 收藏0
  • 前端知识点(二)

    摘要:在给一个目标对象为构造函数的代理对象构造实例时触发该操作,比如在执行时。 1、元素上下垂直居中的方式有哪些? 元素水平垂直居中的方式有哪些? absolute加margin方案 fixed 加 margin 方案 display:table 方案 行内元素line-height方案 flex 弹性布局方案 transform 未知元素宽高解决方案 absolute加mar...

    lbool 评论0 收藏0
  • 前端知识点(二)

    摘要:在给一个目标对象为构造函数的代理对象构造实例时触发该操作,比如在执行时。 1、元素上下垂直居中的方式有哪些? 元素水平垂直居中的方式有哪些? absolute加margin方案 fixed 加 margin 方案 display:table 方案 行内元素line-height方案 flex 弹性布局方案 transform 未知元素宽高解决方案 absolute加mar...

    Alex 评论0 收藏0

发表评论

0条评论

JohnLui

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<