Skip to content

Commit

Permalink
vuex_learn
Browse files Browse the repository at this point in the history
  • Loading branch information
xiannvjiadexiaogouzi authored and xiannvjiadexiaogouzi committed Sep 28, 2020
1 parent 6af5bc6 commit ba48a16
Show file tree
Hide file tree
Showing 14 changed files with 1,811 additions and 4 deletions.
5 changes: 4 additions & 1 deletion vue-learn/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
[原文](./mvvm/mvvm.md)

## vue-router 解析
[原文](./vue-router解析/vue-router解析.md)
[原文](./vue-router解析/vue-router解析.md)

## vuex 解析
[原文](./vuex解析/vuex.md)
34 changes: 31 additions & 3 deletions vue-learn/vue-router解析/vue-router解析.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,13 +246,17 @@ export default MyRouter
### install
将该组件注册成插件,注入`vue`app
`install`里面需要做两件事,第一件是混入(`mixin`)`router`实例,第二件是注册`router-view`组件
- `mixin`混入
- 在`beforeCreate`钩子下调用代码
-
```js
// @function install
MyRouter.install = function (vue) {

// 混入
vue.mixin({
// 查找到根实例组件 绑定当前组件和根实例router对象
// 在Vue被实例化的时候调用以下代码,实现vue的扩展
// 找到vue根实例组件 绑定当前组件和根实例router对象
beforeCreate() {
// 路由根实例
// 只有vue.$options中存在router的才是router的根实例
Expand All @@ -270,17 +274,41 @@ MyRouter.install = function (vue) {
}
})

// 改写vue原型上的$router和$route,指向根路由的router和route
Object.defineProperty(Vue.prototype, '$router', {
get(){
return this._routeRoot.router
}
})

Object.defineProperty(Vue.prototype, '$route', {
get(){
return this._routeRoot.route
}
})

// 注册router-view组件
vue.component('router-view', {
// vue渲染函数
render(h) {
// 拿到当前路径
let current = this._self._routerRoot._router.history.current
let routesMap = this._self._routerRoot._router.routesMap
const current = this._self._routerRoot._router.history.current
const routesMap = this._self._routerRoot._router.routesMap
// 渲染当前组件
return h(routesMap[current])
}
})

// 注册router-link组件
vue.component('router-link', {
props: {
to: String
},
render(h){
// 渲染结果 <a :href="to">xxxx</a>
return h('a', {attrs: {href: '#' + this.to}}, this.$slots.default)
}
})
}
```
Expand Down
Binary file added vue-learn/vuex解析/img/vuex.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
193 changes: 193 additions & 0 deletions vue-learn/vuex解析/srcCode/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import { isObject } from './util'

/**
* Reduce the code which written in Vue.js for getting the state.
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
* @param {Object}
*/
export const mapState = normalizeNamespace((namespace, states) => {
const res = {}
if (__DEV__ && !isValidMap(states)) {
console.error('[vuex] mapState: mapper parameter must be either an Array or an Object')
}
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
})

/**
* Reduce the code which written in Vue.js for committing the mutation
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
export const mapMutations = normalizeNamespace((namespace, mutations) => {
const res = {}
if (__DEV__ && !isValidMap(mutations)) {
console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object')
}
normalizeMap(mutations).forEach(({ key, val }) => {
res[key] = function mappedMutation (...args) {
// Get the commit method from store
let commit = this.$store.commit
if (namespace) {
const module = getModuleByNamespace(this.$store, 'mapMutations', namespace)
if (!module) {
return
}
commit = module.context.commit
}
return typeof val === 'function'
? val.apply(this, [commit].concat(args))
: commit.apply(this.$store, [val].concat(args))
}
})
return res
})

/**
* Reduce the code which written in Vue.js for getting the getters
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} getters
* @return {Object}
*/
export const mapGetters = normalizeNamespace((namespace, getters) => {
const res = {}
if (__DEV__ && !isValidMap(getters)) {
console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object')
}
normalizeMap(getters).forEach(({ key, val }) => {
// The namespace has been mutated by normalizeNamespace
val = namespace + val
res[key] = function mappedGetter () {
if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
return
}
if (__DEV__ && !(val in this.$store.getters)) {
console.error(`[vuex] unknown getter: ${val}`)
return
}
return this.$store.getters[val]
}
// mark vuex getter for devtools
res[key].vuex = true
})
return res
})

/**
* Reduce the code which written in Vue.js for dispatch the action
* @param {String} [namespace] - Module's namespace
* @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
* @return {Object}
*/
export const mapActions = normalizeNamespace((namespace, actions) => {
const res = {}
if (__DEV__ && !isValidMap(actions)) {
console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object')
}
normalizeMap(actions).forEach(({ key, val }) => {
res[key] = function mappedAction (...args) {
// get dispatch function from store
let dispatch = this.$store.dispatch
if (namespace) {
const module = getModuleByNamespace(this.$store, 'mapActions', namespace)
if (!module) {
return
}
dispatch = module.context.dispatch
}
return typeof val === 'function'
? val.apply(this, [dispatch].concat(args))
: dispatch.apply(this.$store, [val].concat(args))
}
})
return res
})

/**
* Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
* @param {String} namespace
* @return {Object}
*/
export const createNamespacedHelpers = (namespace) => ({
mapState: mapState.bind(null, namespace),
mapGetters: mapGetters.bind(null, namespace),
mapMutations: mapMutations.bind(null, namespace),
mapActions: mapActions.bind(null, namespace)
})

/**
* Normalize the map
* normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
* normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
* @param {Array|Object} map
* @return {Object}
*/
function normalizeMap (map) {
if (!isValidMap(map)) {
return []
}
return Array.isArray(map)
? map.map(key => ({ key, val: key }))
: Object.keys(map).map(key => ({ key, val: map[key] }))
}

/**
* Validate whether given map is valid or not
* @param {*} map
* @return {Boolean}
*/
function isValidMap (map) {
return Array.isArray(map) || isObject(map)
}

/**
* Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
* @param {Function} fn
* @return {Function}
*/
function normalizeNamespace (fn) {
return (namespace, map) => {
if (typeof namespace !== 'string') {
map = namespace
namespace = ''
} else if (namespace.charAt(namespace.length - 1) !== '/') {
namespace += '/'
}
return fn(namespace, map)
}
}

/**
* Search a special module from store by namespace. if module not exist, print error message.
* @param {Object} store
* @param {String} helper
* @param {String} namespace
* @return {Object}
*/
function getModuleByNamespace (store, helper, namespace) {
const module = store._modulesNamespaceMap[namespace]
if (__DEV__ && !module) {
console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
}
return module
}
15 changes: 15 additions & 0 deletions vue-learn/vuex解析/srcCode/index.cjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Store, install } from './store'
import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from './helpers'
import createLogger from './plugins/logger'

export default {
Store,
install,
version: '__VERSION__',
mapState,
mapMutations,
mapGetters,
mapActions,
createNamespacedHelpers,
createLogger
}
26 changes: 26 additions & 0 deletions vue-learn/vuex解析/srcCode/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Store, install } from './store'
import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from './helpers'
import createLogger from './plugins/logger'

export default {
Store,
install,
version: '__VERSION__',
mapState,
mapMutations,
mapGetters,
mapActions,
createNamespacedHelpers,
createLogger
}

export {
Store,
install,
mapState,
mapMutations,
mapGetters,
mapActions,
createNamespacedHelpers,
createLogger
}
39 changes: 39 additions & 0 deletions vue-learn/vuex解析/srcCode/mixin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export default function (Vue) {
const version = Number(Vue.version.split('.')[0])

// vue 2.0+
if (version >= 2) {
// 混入
Vue.mixin({ beforeCreate: vuexInit })
} else {
//vue 2.0-
// 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() {
// this => vue实例
const options = this.$options
// store injection
if (options.store) { // vue根实例才有options.store
// 绑定this.$store => this.$options.store
this.$store = typeof options.store === 'function'
? options.store()
: options.store
} else if (options.parent && options.parent.$store) { //其他子组件
// this.$store => 当前组件父组件的$tore(父组件再指向父组件一直指到根实例)
this.$store = options.parent.$store
}
}
}
Loading

0 comments on commit ba48a16

Please sign in to comment.