美文网首页
vuex的简单实现方式

vuex的简单实现方式

作者: 心大的少年 | 来源:发表于2020-05-25 17:56 被阅读0次

vuex的响应式是数据是通过vue的响应式来实现的,也就是使用公共总线的方式,

import Vue from 'vue';

export class Store {
  constructor(options = {}) {
    // 可以利用vue数据的响应,
    this._vm = new Vue({
      data: {
        $store: options.state
      }
    });
    this.state = this._vm._data.$store;
    this.actions = options.actions;
    this.mutations = options.mutations;
    const { dispath, commit } = this;
    // 重写,可以再里面做一些验证什么的,自由发挥
    this.dispath = (type, payload) => dispath.call(this, type, payload); // 重写为action注入commit
    this.commit = (type, payload) => commit.call(this, type, payload);

  }
  dispath(type, payload) {
    const actionParams = { type, payload, commit: this.commit };
    const action = this.actions[type];
    if (!action) {
      console.error(`[vuex] unknown action type: ${type}`);
      return
    }
    action(actionParams);
  }

  commit(type, payload) {
    const mutation = this.mutations[type];
    if (!mutation) {
      console.error(`[vuex] unknown mutation type: ${type}`);
      return
    }
    this.isCommit = true;
    mutation(this.state, payload);
    this.isCommit = false;
  }
}

export function install(Vue) {
  Vue.mixin({ beforeCreate: vuexInit })
}

function vuexInit() {
  const options = this.$options;// 在new Vue的时候传进去的键值对都可以在this.$options里面找到
  if (options.store) {
    this.$store = options.store
  } else if (options.parent && options.parent.$store) {
    this.$store = options.parent.$store
  }
}

export default {
  Store,
  install,
  version: '__VERSION__',
}

相关文章

  • 手摸手教你实现一个 vuex

    参考链接:如何实现一个简单的vuex

  • vue组件之间的几种通讯方式

    1. props和$emit 最简单常用的方式 目录结构 效果图 2. vuex https://vuex.vue...

  • Vue vuex简单实现

  • 手动实现简单的vuex

    官方vuex vue add vuex main.js kstore.js kvuex.js 使用

  • 实现一个简单的vuex

    首先我们先看下vuex的使用方式一般都是下面这样的 有个组件是这样的 我们要实现一个vuex主要有几个要点vuex...

  • Vuex 状态管理

    Vue组件间通信方式 Vuex核心概念和基本使用 购物车案例 模拟实现vuex 一、组件内的状态管理流程 状态管理...

  • vuex

    Vuex介绍: Vuex官网:http://vuex.vuejs.org/ Vuex是实现数据状态管理的技...

  • Vuex简单入门

    今天试了一下Vuex,感觉跟Redux的实现思想类似。再此,简单地总结一下。 什么是Vuex 在Vue中,多组件的...

  • Vuex

    1.Vuex概述 2.Vuex基本使用 3.使用Vuex完成todo案例 1.Vuex概述 Vuex是实现组件全局...

  • 通过Vuex实现Input双向绑定

    通过Vuex实现Input的双向绑定 安装Vuex 引入Vuex 新建store.js 页面中绑定

网友评论

      本文标题:vuex的简单实现方式

      本文链接:https://www.haomeiwen.com/subject/iwuvahtx.html