zoukankan      html  css  js  c++  java
  • 手写Vuex

    let Vue
    //myVuex.js
    class Store {
    constructor(options) {
    this.vm = new Vue({
    data: {
    state: options.state
    }
    })

    let getters = options.getter || {}
    this.getters = {}
    Object.keys(getters).forEach(getterName => {
    Object.defineProperty(this.getters, getterName, {
    get: () => {
    return getters[getterName](this.state)
    }
    })
    })

    let mutations = options.mutations || {}
    this.mutations = {}
    Object.keys(mutations).forEach(mutationName => {
    this.mutations[mutationName] = (arg) => {
    mutations[mutationName](this.state, arg)
    }
    })

    let actions = options.actions
    this.actions = {}
    Object.keys(actions).forEach(actionName => {
    this.actions[actionName] = (arg) => {
    actions[actionName](this, arg)
    }
    })

    }
    //dispatch,commit是方法;其余getter,state是属性!!!
    dispatch(method, arg) {
    this.actions[method](arg)
    }
    commit = (method, arg) => {
    console.log(method);
    console.log(this.mutations);
    this.mutations[method](arg)
    }
    get state() {
    return this.vm.state
    }
    }
    let install = function (vue) {
    Vue = vue
    Vue.mixin({
    beforeCreate() {
    //因为vue实例会加入store,$options的意思就是vue实例的参数
    //该步骤的目的是让this.$store能直接访问到
    if (this.$options && this.$options.store) {
    this.$store = this.$options.store
    } else {
    //let c= a && b; a为true则 c=b; ||时 相反
    this.$store = this.$parent && this.$parent.$store
    }
    }
    })
    }

    let Vuex = {
    Store,
    install
    }

    export default Vuex

    //

  • 相关阅读:
    [Leetcode]Linked List Cycle
    [Leetcode]Excel Sheet Column Number
    [Leetcode]Unique Binary Search Trees
    [Leetcode]Same Tree
    同时访问内外网设置路由信息
    希腊字母表示及读音
    jni入门
    查看某个进程运行时间的几种方法
    企业级hbase HA配置
    存在单点故障的namenode宕机恢复测试
  • 原文地址:https://www.cnblogs.com/alaner/p/15156803.html
Copyright © 2011-2022 走看看