Vuex的使用

Vuex的作用:

一般情况下,组件之间的传值用props、$emit就可以完成,但如果层级比较复杂、项目比较大的情况下会选择使用Vuex,让所有的组件统一在一个地方(Vuex)获取所需要的数据;

store:

1.Vuex 的核心就是store(仓库), “store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)/数据。
2.Vuex和单纯的全局对象的不同点:

  • Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  • 能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化。

store用于存放在组件中需要的数据,需要什么数据就在store中创建什么数据,类型不限;
3.步骤:
3.1:

  • 首先安装vuex;
  • 新建一个store文件夹,里面新建一个store.js文件(必须要和根文件main.js联系起来);
安装 Vuex 之后,来创建一个 store。创建过程直截了当,仅需要提供一个初始 state 对象和一些 mutation:

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: { // 全局访问的state对象
    // 需要使用的初始使用值
    count: 0,
    reg: true,
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ],
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

export default store

3.2:
根文件main.js:

import Vue from 'vue'
import Element from 'element-ui'
import './styles/element-variables.scss'
import '@/styles/index.scss' // global css
import App from './App'
import store from './store'
import router from './router'
//全局混入
import mixin from './mixin/global'
Vue.mixin(mixin)

new Vue({
  el: '#app',
  router,
  store,
  i18n,

  render: h => h(App)
}).$mount('#app')

3.3 在组件中使用(获取数据):
在Vue组件中如果想要访问vuex中的数据,方法是在计算属性computed中返回某个数据状态

// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>
             <p>{{ this.$store.state.reg }}</p>
            `,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM

Getters
  1. 有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它, 但这些方法都比较繁杂,不是我们想要的结果;

  1. Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就类似于vue组件中的computed(计算属性)一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
    Getter 接受 state 作为其第一个参数:
const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: { // 实时监听state变化
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})
  1. 想要访问getter获取其中的函数在组件中使用,通过属性访问的方式实现。Getter 会暴露为 store.getters 对象
// 在vue组件中访问vuex中getters中的函数:
this.$store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Mutations
  1. 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

2.1 没有参数的提交方式:

// 在 store 文件中: 
const store = new Vuex.Store({
  state: {
    count: 1
  },
  // 不允许vue组件传递数据的方式:
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
  // 允许vue组件传递数据的方式:
  mutations: {
    increment (state, n) { // 接收两个参数,一个是stote,
                           // 另外一个是vue组件调用这个函数时传递的数据;
      // 变更状态
      state.count += n
    }
  }
})

2.2 有参数的提交方式:

在Vue组件中如果想要实现这一变更,可以通过commit调用这一函数:

this.$store.commit('increment')

也可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

// store文件中
mutations: {
  increment (state, n) {
    state.count += n
  }
}
// vue 组件中:
this.$store.commit('increment', 10)

2.3 参数是对象的提交方式:

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

// store文件中
mutations: {
  increment (state, payload) { // payload这个参数名可以随意写
    state.count += payload.amount
  }
}
// vue 组件中:
this.$store.commit('increment', {
  amount: 10
})

2.4 参数是包含type属性的对象的提交方式:

// store文件中
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
// vue 组件中:
this.$store.commit({
  type: 'increment',
  amount: 10
})
  1. Mutation 需遵守 Vue 的响应规则
  • 最好提前在你的 store 中初始化好所有所需属性。

  • 当需要在对象上添加新属性时,应该使用 Vue.set(obj, ‘newProp’, 123), 或者以新对象替换 老对象。例如,利用对象展开运算符 (opens new window)我们可以这样写:

state.obj = { ...state.obj, newProp: 123 }
  • Mutation 必须是同步函数(原因: 任何在回调函数中进行的状态的改变都是不可追踪的)
Action
  1. action提交的是mutation, 而不是直接变更状态;
  2. action可以包含任意的异步操作;
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
    // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,
         // 因此你可以调用 context.commit 提交一个 mutation
      context.commit('increment')
    }
  }
})
  1. 在实践中,经常会用到ES2015的参数结构来简化代码,特别是需要调用 commit很多次的时候:
actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
  1. 通过 store.dispatch触发actions:
// 在vue组件中
this.$store.dispatch('increment')
  1. 在actions中可以执行异步操作:
// 在store文件中:
actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

6.actions支持以载荷方式分发,也支持以对象方式分发(触发):

// 在vue组件中:
// 以单个数据形式分发
this.$store.dispatch('incrementAsync', 20)

// 以载荷形式分发
this.$store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
this.$store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
Modules

在store文件夹下新建modules文件夹,然后在modules文件夹下新建modules1.js、modules2.js…

modules1.js(方法1):

const module1 =
{
    state: {
        moudle1Value: 'module1-value',
    },
    mutations: {
        changeModule1(state, newValue) {
            state.moudle1 = newValue
        },
    },
    getters: {
        getModules1(state) {
            return state.moudle1
        }
    },
    actions: {
        useActionChangeModule1({
            commit
        }, newValue) {
            commit('changeModule1', newValue)
        },
    }
}

export default module1

modules2.js(方法2):

const state = {
    moudle2Value: 'module2-value',
}

const mutations = {
    changeModule2(state, newValue) {
        state.moudle2 = newValue
    },
}

const getters = {
    getModule2(state) {
        return state.moudle2
    }
}
const actions = {
    useActionChangeModule2({
        commit
    }, newValue) {
        commit('changeModule2', newValue)
    },
}
export default { state, mutations, actions, getters }

在store文件夹下的index.js文件中注册modules1.js、modules2.js…

import Vue from "vue"
import Vuex from "vuex"
import module1 from "./modules/module1"
import module2 from "./modules/module2"

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        module1,
        module2
    },
})
export default store;

获取state

 computed: {
     ...mapState({
      module1: state => state.module1.moudle1Value,
      module2: state => state.module2.moudle2Value,
       }),
  },

获取getters

computed: {
	getModules1() {
	      return this.$store.getters.getModules1;
	    }.
	...mapGetters(["getModules1"])
  },

commit调用

changeModule1() {
      this.$store.commit("changeModule1", "new module 1");
    },
   ...mapMutations(["changeModule1"])

在这里插入图片描述

  1. 由于使用的是单一状态树,应用的所有状态会集中到一个比较大的对象中。当应用非常复杂时,store对象有可能就变的相当臃肿。为解决这一问题,vuex允许将store分割成“模块”,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
  1. 模块的局部状态
    2.1 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象
const moduleA = {
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}

2.2 对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}
  1. 命名空间
    默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

如果希望模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

命名空间主要解决了,不同模块间重名函数的问题

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          state: () => ({ ... }),
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})

常用方法:

用法:export default  {namespaced: true,

获取getter

...mapGetters("module1", ["getModules1"]) //  映射为 `this.$store.getters.common.getToken`
    // // 方式2
    getModules1() {
      return this.$store.getters.module1.getModules1;
     }

commit调用

changeModule1() {
      this.$store.commit("module1/changeModule1", "new module 1");
    },

    ...mapMutations("module1", [
      "changeModule1" // 将 `this.getTokenData()` 映射为 `this.$store.dispatch('common/getTokenData')`
    ])

dispath调用

changeModule1() {
      this.$store.commit("module1/useActionChangeModule1", "new module 1");
    },

    ...mapActions("module1", [
      "useActionChangeModule1" 
    ])
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值