写给新手同学的vuex快速上手指北

1,570 阅读2分钟

引入

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {...},
    mutations: {...},
    actions: {...}
})

export default store

//main.js
...
import store from './store'
Vue.prototype.$store = store
const app = new Vue({
    store,...
})
...

//test.vue 使用时:
import {mapState,mapMutations} from 'vuex'

State篇

  • state更新实时渲染是基于==computed==这个计算属性的,直接赋给data只能赋值初始值,不会随着state改变实时渲染
<!--state改变不会实时渲染-->
export default {
    data() {
    	return {
    		name:this.$store.state.name,
    	};
    },
}
<!--监听state改变重新渲染视图-->
<template>
    <div>
        {{name}}
    </div>
<template>
export default {
    computed: {
    	name() {
    		return this.$store.state.name;
    	}
    },
}

注意: data中的变量如果和computed中的变量重名,data优先,注意命名

  • 获取多个state值,写多个函数return,很繁琐,所以有==mapState==辅助函数
<!--取多个很冗余,繁琐-->
export default {
    computed: {
    	token(){
    		return this.$store.state.token;
    	},
    	name(){
    		return this.$store.state.name;
    	}
    },
}

<!--mapState 直接取出-->
import { mapState } from 'vuex'
export default {
    computed: mapState([
      'token''name'
    ])
}
  • 我们有局部计算,怎么和mapState一起用?
import { mapState } from 'vuex'
export default {
    computed:{
        getTime(){
            return 123;
        },
        ...mapState([
          'token''name'
        ])
    }
}
  • 我们为它起个别名
<template>
    <div>
        xiaokeai,dahuilang是我们取的别名
        token,name是state的值
        {{xiaokeai}}
    </div>
<template>
<script>
    import { mapState } from 'vuex'
    export default {
        computed:{
            ...mapState({
                xiaokeai:"token",
                dahuilang:"name",
            })
        }
    }
</script>
  • 我们要state和data发生点什么
<template>
    <div>
        假如token的值123;
        balabala的值就是 123皮卡皮
        {{balabala}}
    </div>
<template>
<script>
    import { mapState } from 'vuex'
    export default {
        data(){
            return {
                pikaqiu:"皮卡皮卡"
            }
        }
        computed:{
            ...mapState({
                xiaokeai:"token",
                dahuilang:"name",
                // 为了能够使用 `this` 获取局部状态,使用一个自定义名字的函数
                balabala(state){
                   return state.token + this.pikaqiu;
                }
            })
        }
    }
</script>
  • 取个对象值怎么破?
<template>
	<div>
		{{daSon}}
		{{xiaoSon}}
	</div>
</template>
<script>
    import { mapState } from 'vuex'
    export default {
        data(){
            return {
                pikaqiu:"皮卡皮卡"
            }
        }
        computed:{
            ...mapState({
			daSon: state=>state.obj.yeye.baba.daSon,
			xiaoSon:state=>state.obj.yeye.baba.xiaoSon,
		})
        }
    }
</script>

这种方式取对象写到业务里不直观,也不共用,下节==Getter==有更优的方案

Getter篇

  • Getter是针对state的【对象】值提前做一些处理,以便用的时候直接提取

可以 this.$store.getters.xxx 使用,也可以使用mapGetters辅助函数,==辅助函数注意:== 和state一样,注入在computed中

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		obj: {
			yeye: {
				baba: {
					daSon: "老大",
					xiaoSon: "老二"
				}
			}
		}
	},
	getters: {
        <!--将想要提取或者处理的值这里处理好-->
		getson: state => {
			return state.obj.yeye.baba;
		}
	}
})

export default store


<!--用的时候,和state一样,也可以别名等等操作-->
<template>
	<div>
        {{getson}}
	</div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters([
        getson
    ])
  }
}
</script>

Mutation篇

操作: this.$store.commit("名字","值");

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		token: "vuex的token",
	},
	mutations: {
		setToken(state, val) {
			state.token = val;
		}
	}
})

export default store

mapMutations 辅助函数,和state一样,可以别名, ==注意:== 辅助函数注入在methods中

  methods: {
    ...mapMutations([
      'setToken'
    ])
  }
  
  <!--使用-->
  this.setToken(100); //token修改为100

Mutation 必须是同步函数,不要误解这句话,以为异步不能用,异步可以用在里面,视图的渲染,取值都没有问题,问题在于:调试的时候,一些浏览器调试插件不能正确监听state。所以方便调试,尽量将异步写入action中

Action篇

注意action的 参数不是 state ,而是context,context里面包含commit,state。基本操作:this.$store.dispatch("函数名","值")

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

<!--辅助函数操作  注入在methods中-->
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions([
        "increment"
    ])
  }
}

<!--使用-->
this.increment(123);

module篇

module 目的将store按功能拆分成多个文件,利于维护管理,module 分为2种情况,1.是有命名空间, 2.是没有命名空间

  • 没有命名空间: action、mutation 和 getter 是注册在全局的,所以要注意,方法函数不要设置同名了,如果同名了会都执行。 stete例外是局部。
import Vue from 'vue';
import Vuex from 'vuex';
import moduleA from "./modules/cat.js";
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		token: "vuex的token",
	},
	modules:{
		moduleA
	}
})

export default store;

<!--moduleA.js-->
export default {
	// namespaced: true,
	state: {
	  cat:"我是cat",
	},
	mutations: { 
		setCat(state, val) {
			state.cat = val;
		}  
	},
	actions: { 
			  
	},
	getters: { 
			  
	}
};

  • 无命名空间 取值
this.$store.state.moduleA.cat
或者
...mapState({
	cat:state=>state.moduleA.cat,
}),

不可以(state是局部,不可以这么取):
...mapState([
    "cat"
]),
  • 无命名空间 改变值
和原来一样,因为方法是注册在全局的
this.$store.commit("setCat",666);
或者
...mapMutations([
	"setCat"
])

  • 有命名空间: state, action、mutation 和 getter 是局部的,模块间命名互相不冲突,可以重名。 namespaced 设置为true,即可开启
<!--moduleA.js 文件-->
export default {
	namespaced: true,
	state: {
	  cat:"我是cat",
	}
}
  • 有命名空间取值
this.$store.state.moduleA.cat

或者
<!--注意这里:命名空间的名字带上,在modules注册时候呢个key值-->
<!--也可以别名,方法和之前一样,就是第一个参数是空间名-->
...mapState("moduleA",[
    "cat"
])
  • 有命名空间 改变值
<!--只是第一个参数是空间名,其他操作一样-->
...mapMutations("moduleA",[
	"setCat"
])
this.setCat(888);

或者:

this.$store.commit("moduleA/setCat",666);

最后 plugins

vuex页面刷新会丢失数据,用vuex-persistedstate插件可解决

import createPersistedState from "vuex-persistedstate";

const store = new Vuex.Store({
	state: {},
	mutations: {},
	actions: {},
	getters: {},
	modules:{},
    plugins: [
        createPersistedState({
            storage: window.sessionStorage
        })
    ]
})

export default store