你還不知道 vuex 如何使用? vuex快速上手javascript
當咱們對vuex有了必定的瞭解以後發現隨着項目愈來愈大, 將全部的store單一的存在一個js裏顯然維護和使用起來都不太方便, 這時候咱們最好是將store拆分開,使state、getters、mutations、actions、都單獨管理, 至於vuex提供的module,我的以爲層次多了頁不太適合管理不推薦使用(我的看法) 1、安裝好vue和vuex 用腳手架安裝就好,不會的點一下vue
2、構建目錄 在src目錄下建立store文件夾,和六個js文件java
文件名 | 用處 |
---|---|
states.js | 裏面存放全部的state |
getters.js | 裏面存放全部的state |
mutations.js | 裏面存放全部的mutations |
actions.js | 裏面存放全部的actions |
types.js | 裏面存放全部的types,用來action和mutations的匹配 |
index.js | 固然就是將上面的五個拆分的東西組合起來 |
const state = {
count:0
}
export default state
複製代碼
getter.jsios
const getters = {
docount:(state,getters) => {
return state.counts
}
}
export default getters
複製代碼
types.jsgit
export const SET_COUMT = 'SET_COUMT'
export const SET_COUMT_ADD = 'SET_COUMT_ADD'
export const SET_COUMT_REDUCE = 'SET_COUMT_REDUCE'
複製代碼
mutations.jsgithub
import * as TYPES from './types';
const mutations = {
[TYPES.SET_COUMT](state, v) {
state.count = v;
},
[TYPES.SET_COUMT_ADD](state,v) {
if(v){
state.count += v
}else{
state.count ++
}
},
[TYPES.SET_COUMT_REDUCE](state,v) {
if(v){
state.count -= v
}else{
state.count --
}
}
}
export default mutations
複製代碼
actions.jsvuex
import * as TYPES from './types';
const actions = {
ADD1000(vuex) {
// axios.get("/customer/user_info").then(res => {
// commit(TYPES.SET_COUMT, res.data);
// });
vuex.commit(TYPES.SET_COUMT_ADD, 1000);
},
REdUCE1000(vuex) {
// axios.get("/customer/user_info").then(res => {
// commit(TYPES.SET_COUMT, res.data);
// });
vuex.commit(TYPES.SET_COUMT_REDUCE, 1000);
}
}
export default actions
複製代碼
index.jsaxios
import Vue from 'vue';
import Vuex from 'vuex';
import state from './states';
import getters from './getters';
import mutations from './mutations';
import actions from './actions';
Vue.use(Vuex)
export const store = new Vuex.Store({
state,
getters,
mutations,
actions,
})
複製代碼
到這裏就拆分完畢了,調用方法仍是跟之前是同樣的,只是這樣更容易維護識別度高。函數
4、vuex使用 在main.js裏引入store並初始化 post
<script>
import { mapState , mapMutations , mapActions , mapGetters } from 'vuex';
export default {
data(){
return{
}
},
computed:{
...mapState({
counts:(state) => state.count
}),
...mapGetters({
getternum:'docount'
})
},
methods:{
...mapMutations({
addnum:'SET_COUMT_ADD',
reducenum:'SET_COUMT_REDUCE'
}),
...mapActions({
addmore:'ADD1000',
reducemore:'REdUCE1000'
}),
add(){
this.addnum()
console.log(this.counts,'+1')
},
reduce(){
this.reducenum()
console.log(this.counts,'-1')
},
add1000(){
this.addmore()
console.log(this.counts,'+1000')
},
reduce1000(){
this.reducemore()
console.log(this.counts,'-1000')
}
},
mounted(){
console.log(this.counts,this.$store.state.count,111111111)
}
}
</script>
複製代碼
上面只展現vuex輔助函數調用方法,
原理和方法點擊 ---> 瞭解vuex輔助函數調用方法mp.csdn.net/mdeditor/88…
不想複製粘貼的直接去github:github.com/babybrother…