1.@/store/modules/app.js 设置vuex
import { login as loginApi } from '@/api/login'
// 导入路由跳转
import router from '@/router'
export default {
namespaced: true,
state: () => ({
token: localStorage.getItem('token') || ''
}),
mutations: {
setToken(state, token) {
state.token = token
localStorage.setItem('token', token)
}
},
actions: {
login({ commit }, userInfo) {
return new Promise((resolve, reject) => {
loginApi(userInfo)
.then((res) => {
console.log(res)
commit('setToken', res.token)
// 跳转到首页
router.replace('/')
resolve()
})
.catch((err) => {
reject(err)
})
})
}
}
}
2.@/store/index.js配置使用
import { createStore } from 'vuex'
import app from './modules/app'
export default createStore({
modules: {
app
}
})
3.@/views/login/index.vue使用
//使用vuex
import { useStore } from 'vuex'
const store = useStore()
// 登录
const handleConfirm = () => {
formRef.value.validate(async (valid) => {
if (valid) {
store.dispatch('app/login', form.value)
} else {
// 失败
}
})
}