vuex的簡單使用和模組化寫法

2021-09-24 03:26:46 字數 2338 閱讀 7118

1.新建乙個store資料夾在src目錄下

(1)新建index.js

import vue from 'vue'

import vuex from 'vuex'

import state from './state'

import getters from './getter'

import mutations from './mutation'

import actions from './action'

//vue使用外掛程式都要use一下

vue.use(vuex)

export default new vuex.store()

(2)分別新建state.js,getter.js,mutation.js,action.js檔案

例如state.js(其中localstorage是為了快取,以免頁面重新整理了傳的值就不存在了)

let defaultcity = '北京'

let defaultsignname = '北京'

try

if(localstorage.sightname)

} catch (error)

export default

例如getters.js

export default
例如mutation.js

export default  catch (error) 

},changesignnamecommit(state, sightname) catch (error) }}

action.js

export default ,

changesignname(ctx, sightname)

}

2.開啟main.js

3.在***.vue中使用

(1)普通方式:

在template中使用:

}在script中使用:

獲取state中物件的值:   this.$store.state.city

使用mutations改變state中物件的值

this.$store.commit('changecitycommit',this.city)

使用actions改變state中物件的值:

this.$store.dispatch('changecitycommit',this.city)

(2)使用mapstate,mapaction

用上面的寫小專案還可以,大專案最好使用模組化,方便管理各個模組的vuex邏輯

1.同樣在src目錄下新建store資料夾

index.js的內容:

// 組裝模組並匯出 store 的地方

import vue from 'vue'

import vuex from 'vuex'

import cart from './modules/cart'

import webstorage from './modules/webstorage'

import mainindex from './modules/mainindex'

import loading from './modules/loading'

vue.use(vuex)

export default new vuex.store(,

strict: process.env.node_env !== 'production' // 嚴格模式

})

需要引入進index.js的檔案如cart.js,loading.js等的語法基本一致,邏輯就不寫了

const state = 

const getters =

// action非同步操作

const actions =

//mutaions接收:

const mutations =

export default

同樣在main.js中引入,至於使用就和之前一致

vuex的模組化使用

store檔案如下 1.modules下檔案是模組化的劃分,裡面的js有state,action,mutations.然後通過 export default 方式匯出。2.index.js中匯出的格式如下 new vuex.store mutations actions getters 所以inde...

Vuex的模組化

目錄 1.在store資料夾下建立modules資料夾,modules資料夾下的index.js用來彙總vuex的模組,並統一暴露。這樣只需在store的配置中引入modules即可。彙總所有vuex的模組 import home from home import login from login ...

vuex模組化設定

import vue from vue import vuex from vuex vue.use vuex 首先宣告乙個需要全域性維護的狀態 state,比如 我這裡舉例的resturantname const modulesfiles require.context modules false,...