赞
踩
在我们平常做项目的过程中,经常会使用到公共的数据,这个时候Vuex是一个很好的仓库,它可以用来存储公共的数据 。
总共有五个: state ,getters,muaction,action,module。
现在我们具体分析一下怎么去使用。
- import Vue from 'vue'
- import Vuex from 'vuex'
- import getters from './getters'
- import app from './modules/app'
- import settings from './modules/settings'
- import user from './modules/user'
-
- Vue.use(Vuex)
-
- const store = new Vuex.Store({
- modules: {
- app,
- settings,
- user
- },
- getters
- })
-
- export default store

分析:
- import getters from './getters'
- import app from './modules/app'
- import settings from './modules/settings'
- import user from './modules/user'
导入并且注册成模块。
- // 将token存储vuex中,vuex刷新就没了,解决刷新就没了的问题
- import Cookiejs from 'js-cookie'
- import { sysLogin } from '@/api/login'
- import { Message } from 'element-ui'
- import { sysProfile } from '@/api/user'
- const state = {
- // 有就取token 没有就为空
- token: Cookiejs.set('hr67') || '',
- userInfo: ''
- }
- const mutations = {
- setToken(state, value) {
- state.token = value
- Cookiejs.set('hr67', value)
- },
- setUserInfo(state, value) {
- state.userInfo = value
- }
- }
- const actions = {
- // 登录
- async toLogin(store, from) {
- const res = await sysLogin(from)
- Message.success('登录成功')
- store.commit('setToken', res.data)
- },
- // 获取用户信息
- async getUserInfo({ commit }) {
- const res = await sysProfile()
- commit(' setUserInfo', res.data)
- }
- }
- const getters = {}
- export default {
- namespaced: true,
- state,
- mutations,
- getters,
- actions
- }

分析:
- const state = {
- // 有就取token 没有就为空
- token: Cookiejs.set('hr67') || '',
- userInfo: ''
- }
- const mutations = {
- setToken(state, value) {
- state.token = value
- Cookiejs.set('hr67', value)
- },
- setUserInfo(state, value) {
- state.userInfo = value
- }
- }
- const actions = {
- // 登录
- async toLogin(store, from) {
- const res = await sysLogin(from)
- Message.success('登录成功')
- store.commit('setToken', res.data)
- },
- // 获取用户信息
- async getUserInfo({ commit }) {
- const res = await sysProfile()
- commit(' setUserInfo', res.data)
- }
- }
分析
sysLogin方法sysProfile这两个方法都通过:
- import { sysLogin } from '@/api/login'
- import { sysProfile } from '@/api/user'
导入进来了
通过commit来触发mutations里面的方法。
然后在mutation里面进行变量的修改。
触发state的唯一方法,就是mutations。
这是在本模块进行触发的。
如果在其它的页面进行触发呢?
假设点击登录页面进行触发:
- submit() {
- this.$refs.form.validate(async(result) => {
- if (result) {
- // const res = await sysLogin(this.form)
- // this.$store.commit('user/setToken', res.data)
- // console.log(res)
- // this.$message.success('验证成功')
- await this.$store.dispatch('user/toLogin', this.form)
- this.$router.push('/')
- }
- })
- }
举例:
await this.$store.dispatch('user/toLogin', this.form)
这个类似于计算属性。
注册成不同的模块
因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。