vue中使用vuex(新增,修改,獲取,應用)
阿新 • • 發佈:2022-02-22
1. vue 專案中 src 底下建立一個 store 資料夾 => 建立一個 index.js 和 一個 gttters.js 檔案
2.sotre 資料夾底下建立一個 modules 資料夾 => 建立 user.js 和 setting.js 檔案
如下圖所示:
index.js 資料夾內容:
import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' import settings from './modules/settings' import getters from './getters' Vue.use(Vuex) const store = new Vuex.Store({ //這裡 store 的應用對應著資料夾中的順序。 例如:getters 是直接放在 store 資料夾底下的。 user 和 settings 是放在 modules 資料夾底下的 modules: { user, settings }, getters }) export default store
getters.js 檔案內容:
const getters = { //這裡只快取個人資訊和 token 做例子使用。例子: 引數名稱 : state => state. store資料夾底下的 modules 資料夾底下的 JS子檔案的名稱 . 引數名字。 例如: state => state 點 store 資料夾底下的 modules 資料夾底下的 user.js 檔案 定義的例項 點
引數名字 =》 token 和 userInfo token: state => state.user.token, userInfo : state => state.user.userInfo, } export default getters
store資料夾底下的 modules 資料夾底下的 user.js 檔案內容:
import { getInfo} from '@/api/login' // 這裡引入的方法只作為展示使用,不作為實際使用 import { getToken } from '@/utils/auth' const user = { state: { token: getToken(), userInfo :{}, }, mutations: { // 這裡設定方法名字要和下面接收的方法名字相對應 SET_TOKEN: (state, token) => { state.token = token }, SET_USERINFO: (state, user)=>{ state.userInfo = user }, }, actions: { // 獲取使用者資訊 GetInfo({ commit, state }) { return new Promise((resolve, reject) => { getInfo(state.token).then(res => { //這裡的 getInfo 要和上面引入的方法名字相同,自行引入,傳參要和你 api 設定的接收引數一樣 const user = res.user commit('SET_USERINFO',res.user) // 這裡 commit 設定的屬性要和上面的 mutations 裡面設定的方法名字相對應 resolve(res) }).catch(error => { reject(error) }) }) }, } } export default user
store資料夾底下的 modules 資料夾底下的 settings.js 檔案內容:
// 這個資料夾建立例項和引數接收值 const mutations = { CHANGE_SETTING: (state, { key, value }) => { if (state.hasOwnProperty(key)) { state[key] = value } } } const actions = { changeSetting({ commit }, data) { commit('CHANGE_SETTING', data) } } export default { mutations, actions }
mian.js 檔案中掛載
import store from './store' //引入 store 資料夾 import router from './router' //本地路由懶載入 new Vue({ //最後匯出即可 el: '#app', router, store, render: h => h(App) })
應用: 由於 store 掛載在 main.js 檔案了,所以不需要每一個地方都去引用 store 檔案,只需要直接使用。
this.$store.getters.userInfo //可以直接獲取到資料,可以通過 .vue 檔案在 created 裡面直接輸出 this.$store.getters 來檢視是否有值或者資料,如果沒有可以看看 moudules 資料夾中的 user.js 有沒有在 例項 state 裡面設定引數值,再看看下面 mutations 裡面有沒有設定
方法來接收值,最後再看看 actions 裡面有沒有用 commit 去修改 state 裡面的值,看看 commit 設定的方法 是否和上面的 mutations 設定的方法名字相同,後端是否返回。 到了這一步資料問題基本上都能定位出來是哪裡的出現的錯誤了
修改: 由於store 掛載在 main.js 檔案中,所以不需要每個地方都去引用 store 檔案,直接使用即可
store.commit(" 對應著 modules 資料夾中的 底下 js 檔案中的方法名字 ", 要修改的值); 例如: store.commit('SET_USERINFO',res.user); // 備註: 這裡的 SET_USERINFO 對應著我 store 資料夾底下的 modules 資料夾 底下的 user.js 的 SET_USERINFO 方法。 這裡的 res.user 對應著介面返回的值,自行修改