vue3.2 登录
作者:互联网
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 {
// 失败
}
})
}
标签:登录,app,vue3.2,token,import,login,vuex,store 来源: https://blog.csdn.net/grow_/article/details/123100420