首先贴图
访问store.state中的xxx
const store = new Vuex.Store({
state: {
num: 0
}
其他页面中访问
<template>
<div id="user">
user
<!--{{$store.state.num}}-->
<!--{{zxd}}-->
<!--{{countPlusLocalState}}-->
{{num}}
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
// computed: mapState({
// 第一种接受数据方法
// // hhh: state => state.num,
// 第二种接受数据方法
// // zxd : 'num'
// 第三种接受数据方法
// countPlusLocalState(state){
// return state.num + 100
// }
// }),
//第四种接收数据的方法
computed:mapState(['num'])
</script>
<style scoped>
</style>
** js是单线程,同步即排队,A事件做完去做B事件,B事件做完去做C事件
异步即不等待,我可以先执行B事件,也可以先执行C事件,而不用等A-B-C
异步事件常用的有setTimeout(), setInterval() **
同步:
mutation(同步)
vuex中更改store中的值,只能通过commit去调用mutation中的事件。而非直接改变 store.state.xxx 例如
const store = new Vuex.Store({
state: {
num: 0
isShow:fales
},
mutations : {
show(state){
state.isShow = true
}
add(state,n){
state.num+=n;
},
del(state,n){
state.num-=n;
}
}
其他页面中要访问
<template>
<div id="user">
{{num}}
//commit:同步操作,写法:this.$store.commit('mutations方法名',值)
<!--<button @click="$store.commit('show')">add</button>-->
<!--<button @click="$store.commit('add',10)">add</button>-->
<!--<button @click="$store.commit('del',10)">del</button>-->
<button @click="add(2)">add</button>
<button @click="del(1)">del</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed:{
...mapState(['num']),
he(){
return 'hhehehe'
}
},
name: "user",
methods:{
...mapMutations(['show','add','del'])
},
</script>
<style scoped>
</style>
异步:
Action(异步)
通过 showsync(){
context.commit('show (这里的show是mutation中的事件名)')
}
例如
const store = new Vuex.Store({
state: {
num: 0
isShow:fales
},
mutations : {
show(state){
state.isShow = true
}
},
actions: {
showsync (context) {
context.commit('show')
}
其他页面中要访问
<template>
<div id="user">
{{num}}
//dispatch:异步操作,例如向后台提交数据,this.$store.dispatch('mutations方法名',值)
//commit:同步操作,写法:this.$store.commit('mutations方法名',值)
// 第一种方式访问
// this.$store.dispatch('showsync') ,用法跟mutation差不多
</div>
</template>
<script>
import { mapState, mapMutations,mapActions } from 'vuex';
export default {
computed:{
...mapState(['num']),
he(){
return 'hhehehe'
}
},
name: "user",
methods:{
...mapMutations(['show','add','del']),
...mapActions(['showsync'])
},
</script>
<style scoped>
</style>
如果是上面这种情况,通常同步请求就能解决,actions一般用来解决异步,这里官方写得很好,
贴上链接
vuex.vuejs.org/zh/guide/ac…
针对中小型项目,上面几种已经够用,getter相当于计算属性,难度不大,这里不做讨论,可以自行看文档
vuex.vuejs.org/zh/guide/ge…
有一个小细节,文档中有个写法我一直百思不得其解,后来看别人写的,明白了
Module
如果你用过vue-element-admin,你一定得了解vuex中的module, 暂时贴个文档的链接,有时间再更