网站首页 > 技术文章 正文
let Vue 
class Store{
    constructor(options){
        this.state = new Vue({   // 强依赖   state 的变化 触发视图的变化
            data:options.state
        })
        this.mutations = options.mutations
        this.actions  = options.actions
        options.getters && this.handleGetters(options.getters)
    }
  // commit接受type和业务入参到mutations
    commit=(type,arg)=>{
        console.log(this)
        this.mutations[type](this.state,arg)
    }
  //发送dispatch到action
    dispatch(type,arg){
        this.actions[type]({
            commit:this.commit,
            state:this.state
        },arg)
    }
    handleGetters(getters){
        this.getters = {};
         // 遍历getters所有key
        Object.keys(getters).forEach(key=>{
            // 为this.getters定义若干属性,这些属性是只读的
            // $store.getters.score
            Object.defineProperty(this.getters,key,{  //每次获取this.getters 的所有属性时 都会触发get
                get:()=>{
                    return getters[key](this.state)
                }
            })
        })
    }
}
function install(_Vue){
    Vue = _Vue
    Vue.mixin({
        beforeCreate() {
            if(this.$options.store){
                Vue.prototype.$store = this.$options.store
            }
        },
    })
}
export default {Store,install}使用:
import Vue from "vue";
import Vuex from "./kvuex";
Vue.use(Vuex);
export default new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state, n = 1) {
      state.count += n;
    }
  },
  getters: {
    score(state) {
      return `共扔出:${state.count}`
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit("increment", 2);
      }, 1000);
    }
  }
});
猜你喜欢
- 2024-09-29 Vue实战——vue+router+vuex导航守卫进行身份验证
- 2024-09-29 shopping开源项目用vue+vue-router+vuex实现电商网站基本功能
- 2024-09-29 Vuex状态管理(vuex状态管理几种状态)
- 2024-09-29 vue2视频教程系列第二十七节—vuex中getters和actions的使用
- 2024-09-29 Vuex 学习笔记(vuex视频教学)
- 2024-09-29 Vue 3学习:4. 集成vuex(vue集成js)
- 2024-09-29 Vue组件间通信(vue组件间通信的方法)
- 2024-09-29 vue-admin-template调用action获取用户资料
- 2024-09-29 vuex的实现以及数据流向(vuex单向数据流图)
- 2024-09-29 vue中如何使用vuex的简单案列(vuex怎样使用)
- 最近发表
- 
- 聊一下 gRPC 的 C++ 异步编程_grpc 异步流模式
- [原创首发]安全日志管理中心实战(3)——开源NIDS之suricata部署
- 超详细手把手搭建在ubuntu系统的FFmpeg环境
- Nginx运维之路(Docker多段构建新版本并增加第三方模
- 92.1K小星星,一款开源免费的远程桌面,让你告别付费远程控制!
- Go 人脸识别教程_piwigo人脸识别
- 安卓手机安装Termux——搭建移动服务器
- ubuntu 安装开发环境(c/c++ 15)_ubuntu安装c++编译器
- Rust开发环境搭建指南:从安装到镜像配置的零坑实践
- Windows系统安装VirtualBox构造本地Linux开发环境
 
- 标签列表
- 
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (77)
- vector线程安全吗 (73)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)
 
