寫給新手同窗的vuex快速上手指北

引入

//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優先,注意命名vue

  • 獲取多個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==有更優的方案vuex

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("名字","值");bash

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中session

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

Mutation 必須是同步函數,不要誤解這句話,覺得異步不能用,異步能夠用在裏面,視圖的渲染,取值都沒有問題,問題在於:調試的時候,一些瀏覽器調試插件不能正確監聽state。因此方便調試,儘可能將異步寫入action中app

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插件可解決ui

import createPersistedState from "vuex-persistedstate";

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

export default store
複製代碼
相關文章
相關標籤/搜索