mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

vue store #36

Open mcya opened 6 years ago

mcya commented 6 years ago

vue store 状态管理

对比 vue store && react reduce

mcya commented 6 years ago

配置

  1. 新建文件夹store store\store.js

  2. 构建页面基本内容,需引入 Vuex

    
    import Vue from 'vue';
    import Vuex from 'vuex';

// 这些文件存储 store 的变量,以文件的形式引入能处理不同情况下的文件,大一点的项目建议如此,小项目亦可 import core from '../storeConfigs/core'; //常规通用store import dictModule from '../storeConfigs/dictModule'; //特殊处理store

/使用Vuex/ Vue.use(Vuex)

export default new Vuex.Store({ // module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。 modules: { core, //响应core的文件声明的变量 dictModule }, strict: true })


3. `main.js`需要获取模块并使用

import store from './store/store';

new Vue({ store, //剩余的是router 等其他需要声明的东西 })

mcya commented 6 years ago

引入文件的配置,同常规的声明变量一样。

  const state = { state1: true, state2: "神啊 赐我个妞吧"},
  const mutations = {
    fun1(val, val2) {
      localStorage.setItem("localStorageString", val);
      localStorage.setItem("localStorageObject", JSON.stringify(val2));// 假设val2为对象
    },
    fun2(val) {},
    fun3(val) {},
  },
  const getters = {},
  const actions = {}

// 引变量即可
export default {
  state,
  mutations,
  getters,
  actions
}
mcya commented 6 years ago

store中存值和取值

// set
// this.$store.commit('你的名字', val)
$ eg: ` this.$store.commit('state1', false) `

// get
// this.$store.state.在store中对应的变量名
$ eg: ` this.$store.state.core.state2 `