![logo](https://image.upwqy.com/asset/images/logo.gif)
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1.在项目根目录下创建store
目录,并创建如图的文件。
1.1 index.js
文件代码
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters.js'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
1.2 getters.js
文件
const getters = {
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name,
}
export default getters
1.3 user.js
文件
import {getToken, setToken, removeToken} from '@/utils/auth'
import {login, smsLogin} from '@/api/api.js'
const state = {
token: getToken(),
name: '',
avatar: '',
mobile: '',
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
}
const actions = {
// 用户登录
login({commit}, userInfo) {
const {mobile, password} = userInfo
return new Promise((resolve, reject) => {
login({mobile: mobile.trim(), password: password}).then(response => {
const {data} = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
smsLogin({commit}, userInfo) {
const {mobile, sms_code} = userInfo
return new Promise((resolve, reject) => {
smsLogin({mobile: mobile.trim(), password: sms_code}).then(response => {
const {data} = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
}
export default {
namespaced: true,
state,
mutations,
actions
}
1.4 app.js
文件
const state = {
loginMode: 'password'
}
const mutations = {
SET_LOGIN_MODE: (state, loginMode) => {
state.loginMode = loginMode
},
}
const actions = {
}
export default {
namespaced: true,
state,
mutations,
actions
}
2. 在main.js
文件中增加配置
import Vue from 'vue'
import App from './App'
import store from '@/store/index.js'
import * as api from '@/api/api.js'
import '@/styles/index.scss';
Vue.config.productionTip = false
Vue.prototype.$api = api
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
3.在项目中使用
3.1 获取属性值
this.$store.getters.name
3.2 调用actions
this.$store.dispatch('user/login', this.loginForm).then(() => {
uni.showToast({
title:'登录成功',
icon:'none'
})
})
发布时间 : 2023-03-01,阅读量:855 , 分类: Vue