实现vuex原理的示例

效果图如下:

1. 准备好环境

使用 vue/cil 初始化项目配置:

npm install -g @vue/cli //全局安装@vue/cli vue create demo-vue //创建项目

yarn add vuex安装vuex创建一个store文件夹并使用:

2. 实现目的

stroe/index.js内容如下:(我们的目的将引入自写的vuex实现vuex基础功能)

import Vue from 'vue'
import Vuex from 'vuex'
// import Vuex from './myvuex'   //我们实现的 青铜版vuex
// import Vuex from './myvuexplus' //我们实现的 白银版vuex

Vue.use(Vuex) //执行install方法 将new Vuex.Store挂载到this.$store

export default new Vuex.Store({
 state: {
  counter: 0,
  userData: {
   name: '时间',
   age: 18
  }
 },
 getters: {
  name(state) {
   return state.userData.name
  }
 },
 mutations: {
  add(state) {
   state.counter++
  },
  updateName(state, payload) {
   state.userData.name = payload
  }
 },
 actions: {
  add({ commit }) {
   setTimeout(() => {
    commit('add')
   }, 1000);
  }
 }
})
  • 青铜版vuexmyvuex.js代码如下:
let Vue
class Store {
 constructor(options) {
  this._vm = new Vue({
   data: {
    state: options.state
   }
  })

  let getters = options.getters
  this.getters = {}
  Object.keys(getters).forEach((val) => {
   Object.defineProperty(this.getters, val, { //getters响应式
    get: () => {
     return getters[val](this.state)
    }
   })
  })

  this._actions = Object.assign({}, options.actions)
  this._mutations = Object.assign({}, options.mutations)
 }

 // get/set state目的:防止外部直接修改state
 get state() {
  return this._vm.state
 }
 set state(value) {
  console.error('please use replaceState to reset state')
 }

 commit = (funName, params) => { //this执行问题
  // 在mutations中找到funName中对应的函数并且执行
  this._mutations[funName](this.state, params)
 }

 dispatch(funName, params) {
  this._actions[funName](this, params)
 }
}

function install(vue) {
 Vue = vue
 vue.mixin({
  beforeCreate () {
   // 将 new Store() 实例挂载到唯一的根组件 this 上
   if (this.$options?.store) {
    this.$store = this.$options.store
   } else {
    this.$store = this.$parent && this.$parent.$store
   }
  }
 })
}

export default {
 Store,
 install
}

青铜版vuex this.$stroe:

  • 白银版vuexmyvuexplus.js代码如下:
let _Vue
const install = function(Vue, opts) {
 _Vue = Vue
 _Vue.mixin({ // 因为我们每个组件都有 this.$store这个东西,所以我们使用混入模式
  beforeCreate () { // 从根组件向子组件遍历赋值,这边的 this 就是每个 Vue 实例
   if (this.$options && this.$options.store) { // 这是根节点
    this.$store = this.$options.store
   } else {
    this.$store = this.$parent && this.$parent.$store
   }
  }
 })
}

class ModuleCollection {
 constructor(opts) {
  this.root = this.register(opts)
 }

 register(module) {
  let newModule = {
   _raw: module,
   _state: module.state || {},
   _children: {}
  }
  Object.keys(module.modules || {}).forEach(moduleName => {
   newModule._children[moduleName] = this.register(module.modules[moduleName])
  })
  return newModule
 }
}

class Store {
 constructor(opts) {
  this.vm = new _Vue({
   data () {
    return {
     state: opts.state // 把对象变成响应式的,这样才能更新视图
    }
   }
  })

  this.getters = {}
  this.mutations = {}
  this.actions = {}

  // 先格式化传进来的 modules 数据
  // 嵌套模块的 mutation 和 getters 都需要放到 this 中
  this.modules = new ModuleCollection(opts)
  console.log(this.modules)

  Store.installModules(this, [], this.modules.root)
 }

 commit = (mutationName, value) => { // 这个地方 this 指向会有问题,这其实是挂载在实例上
  this.mutations[mutationName].forEach(f => f(value))
 }

 dispatch(actionName, value) {
  this.actions[actionName].forEach(f => f(value))
 }

 get state() {
  return this.vm.state
 }
}
Store.installModules = function(store, path, curModule) {
 let getters = curModule._raw.getters || {}
 let mutations = curModule._raw.mutations || {}
 let actions = curModule._raw.actions || {}
 let state = curModule._state || {}

 // 把子模块的状态挂载到父模块上,其他直接挂载到根 store 上即可
 if (path.length) {
  let parent = path.slice(0, -1).reduce((pre, cur) => {
   return pre[cur]
  }, store.state)
  _Vue.set(parent, path[path.length - 1], state)
 }

 Object.keys(getters).forEach(getterName => {
  Object.defineProperty(store.getters, getterName, {
   get: () => {
    return getters[getterName](state)
   }
  })
 })

 Object.keys(mutations).forEach(mutationName => {
  if (!(store.mutations && store.mutations[mutationName])) store.mutations[mutationName] = []
  store.mutations[mutationName].push(value => {
   mutations[mutationName].call(store, state, value)
  })
 })

 Object.keys(actions).forEach(actionName => {
  if (!(store.actions && store.actions[actionName])) store.actions[actionName] = []
  store.actions[actionName].push(value => {
   actions[actionName].call(store, store, value)
  })
 })

 Object.keys(curModule._children || {}).forEach(module => {
  Store.installModules(store, path.concat(module), curModule._children[module])
 })

}

// computed: mapState(['name'])
// 相当于 name(){ return this.$store.state.name }
const mapState = list => { // 因为最后要在 computed 中调用
 let obj = {}
 list.forEach(stateName => {
  obj[stateName] = () => this.$store.state[stateName]
 })
 return obj
}

const mapGetters = list => { // 因为最后要在 computed 中调用
 let obj = {}
 list.forEach(getterName => {
  obj[getterName] = () => this.$store.getters[getterName]
 })
 return obj
}

const mapMutations = list => {
 let obj = {}
 list.forEach(mutationName => {
  obj[mutationName] = (value) => {
   this.$store.commit(mutationName, value)
  }
 })
 return obj
}

const mapActions = list => {
 let obj = {}
 list.forEach(actionName => {
  obj[actionName] = (value) => {
   this.$store.dispatch(actionName, value)
  }
 })
 return obj
}

export default {
 install,
 Store,
 mapState,
 mapGetters,
 mapMutations,
 mapActions
}

白银版vuex this.$stroe:

3. App.vue 内使用自写的vuex:

<template>
 <div id="app">
  <button @click="$store.commit('add')">$store.commit('add'): {{$store.state.counter}}</button>
  <br>
  <button @click="$store.commit('updateName', new Date().toLocaleString())">$store.commit('updateName', Date): {{$store.getters.name}}</button>
  <br>
  <button @click="$store.dispatch('add')">async $store.dispatch('add'): {{$store.state.counter}}</button>
 </div>
</template>
<script>
...

以上就是实现vuex原理的示例的详细内容,更多关于实现vuex原理的资料请关注我们其它相关文章!

(0)

相关推荐

  • 如何手写一个简易的 Vuex

    前言 本文适合使用过 Vuex 的人阅读,来了解下怎么自己实现一个 Vuex. 基本骨架 这是本项目的src/store/index.js文件,看看一般 vuex 的使用 import Vue from 'vue' import Vuex from './myvuex' // 引入自己写的 vuex import * as getters from './getters' import * as actions from './actions' import state from './stat

  • 在Vuex中Mutations修改状态操作

    上篇是读取state,这篇是修改状态.即如何操作Mutations. 一. $store.commit( ) Vuex提供了commit方法来修改状态 1.store.js文件 const mutations={ add(state){ state.count++ }, reduce(state){ state.count-- } } 2.在button上的修改方法 <button @click="$store.commit('add')">+</button>

  • vuex 多模块时 模块内部的mutation和action的调用方式

    vue在做大型项目时,会用到多状态管理,vuex允许我们将store分割成多个模块,每个模块内都有自己的state.mutation.action.getter.模块内还可以继续嵌套相对应的子模块. 为了巩固我自己对store多模块的一些基本认识,写了个简单的多模块实例,下图为我自己创建的store的目录结构,modules文件夹内的模块,在实际项目中还可以继续分开类似store目录下的多文件结构,也就是单独的模块文件夹,方便后期修改. store目录结构 ./store/index.js的代码

  • vuex中store存储store.commit和store.dispatch的用法

    代码示例: this.$store.commit('loginStatus', 1); this.$store.dispatch('isLogin', true); 规范的使用方式: // 以载荷形式 store.commit('increment',{ amount: 10 //这是额外的参数 }) // 或者使用对象风格的提交方式 store.commit({ type: 'increment', amount: 10 //这是额外的参数 }) 主要区别: dispatch:含有异步操作,数

  • vuex分模块后,实现获取state的值

    问题:vuex分模块后,一个模块如何拿到其他模块的state值,调其他模块的方法? 思路: 1.通过命名空间取值--this.$store.state.car.list // OK 2.通过定义该属性的getter方法,因方法全局注册,不存在命名空间,可以通过this直接调用. this.$store.state.car.carGetter 我在car模块中自己的定义了state, getters, this.$store.state.car.list可以拿到值. 但是,this.$store.

  • vuex实现购物车的增加减少移除

    本文实例为大家分享了vuex实现购物车增加减少移除的具体代码,供大家参考,具体内容如下 1.store.js(公共的仓库) import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { carList: [] //购物车的商品 }, mutations: { // 加 addCar(state, params) { let CarCon = state.ca

  • Vuex实现购物车小功能

    Vuex实现购物车功能(附:效果视频),供大家参考,具体内容如下 功能描述: 加购 删除 加减 全选反选 选中计算总价 存储 整体演示效果如下: 首先介绍一下Vuex: Vuex 实例对象属性 主要有下面5个核心属性: state : 全局访问的state对象,存放要设置的初始状态名及值(必须要有) mutations : 里面可以存放改变 state 的初始值的方法 ( 同步操作–必须要有 ) getters: 实时监听state值的变化可对状态进行处理,返回一个新的状态,相当于store的计

  • 解决vuex数据页面刷新后初始化操作

    在vue项目的开发中经常会用到vuex来进行数据的存储,然而在开发过程中会出现刷新后页面的vuex的state数据初始化问题!下面是我用过的解决方法 1.利用storage缓存来实现vuex数据的刷新问题 我们可以在mutation等vuex的方法中对于数据进行改变时,将数据同时存储进我们的本地浏览器缓存中:下面是我在mutation中写的方法: 同步将数据的更改保存,也可以在页面调用vuex的mutation方法时同步更改:但是这种方法只能针对少量的数据需要保持不刷新,在真正的卡发中并不适用

  • 解决VUEX的mapState/...mapState等取值问题

    有木有发现你页面的this.$store,一般都正常,但是总有那么几次,成为你页面报错的罪魁祸首!,那其实除了和vue的生命周期有关以外,还跟store取值的方式有关,下面就说一下新大陆之--mapState mapMutations mapGetters的使用 简单说一下我对mapState的理解,字面意思就是把store中state 的值遍历出来,任你取用,就不用写this.$store.getters.getState.openId等这么长的取值了,同理,mapMutations mapG

  • Vue.js中使用Vuex实现组件数据共享案例

    当组件中没有关联关系时,需要实现数据的传递共享,可以使用Vuex 先不管图片 一.安装 在vue cli3中创建项目时勾选这个组件就可以了 或者手动安装 npm install store --save 二.使用 main.js store.js .vue文件 图片中的js文件中有 三部分 分别与图片上对应 1. state中存储数据 2. 而数据的修改需要先经过action的dispatch方法 (不需要异步获取的数据可以不经过这一步,如上图) 3. 然后经过matations的commit方

  • 对vuex中store和$store的区别说明

    这里写自定义目录标题 <router-link to="/login">{{ $store.state.userName }}</router-link> <router-link to="/login">{{ store.state.userName }}</router-link> <router-link to="/login">{{ this.store.state.userNa

随机推荐