用vue2写登录校验模块
时间: 2023-07-18 13:25:16 浏览: 48
好的,我可以为您提供一个简单的示例代码,用于Vue 2中的登录校验模块。在这个示例中,我们将使用Vue Router和Vuex库来实现登录校验。
首先,我们需要在Vue项目中安装Vue Router和Vuex库。您可以使用以下命令进行安装:
```
npm install vue-router vuex --save
```
接下来,我们可以创建一个名为`auth.js`的Vuex模块来处理用户身份验证。该模块将包括以下内容:
```javascript
import api from '@/services/api'
const state = {
user: null,
loggedIn: false
}
const mutations = {
SET_USER(state, user) {
state.user = user
state.loggedIn = true
},
CLEAR_USER(state) {
state.user = null
state.loggedIn = false
}
}
const actions = {
async login({ commit }, { username, password }) {
try {
const response = await api.post('/login', { username, password })
const user = response.data.user
commit('SET_USER', user)
} catch (error) {
console.error(error)
commit('CLEAR_USER')
}
},
async logout({ commit }) {
try {
await api.post('/logout')
} catch (error) {
console.error(error)
} finally {
commit('CLEAR_USER')
}
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
```
在这个模块中,我们定义了一个名为`state`的对象,它包含了用户对象和一个名为`loggedIn`的布尔值,用于指示用户是否已登录。我们还定义了两个名为`mutations`和`actions`的对象,用于处理用户登录和注销操作。
在`mutations`对象中,我们定义了两个函数,`SET_USER`和`CLEAR_USER`,用于设置和清除用户对象和`loggedIn`状态。
在`actions`对象中,我们定义了两个异步函数,`login`和`logout`,用于处理用户登录和注销操作。在`login`函数中,我们通过发送POST请求到服务器来验证用户身份。如果验证成功,我们将用户对象存储在`state`对象中并将`loggedIn`状态设置为true。如果验证失败,我们将清除用户对象并将`loggedIn`状态设置为false。
接下来,我们可以定义一个名为`AuthGuard`的路由守卫,用于检查用户是否已登录。如果用户未登录,则重定向到登录页面。以下是`AuthGuard`的示例代码:
```javascript
import store from '@/store'
export default (to, from, next) => {
if (store.state.auth.loggedIn) {
next()
} else {
next('/login')
}
}
```
在这个守卫中,我们检查`store.state.auth.loggedIn`状态。如果该状态为true,则表示用户已登录,我们将继续访问目标路由。否则,我们将重定向到登录页面。
最后,我们可以在需要进行身份验证的路由中使用`AuthGuard`守卫。以下是使用守卫的示例代码:
```javascript
import AuthGuard from '@/guards/AuthGuard'
export default [
{
path: '/',
component: Home,
beforeEnter: AuthGuard
},
{
path: '/dashboard',
component: Dashboard,
beforeEnter: AuthGuard
}
]
```
在这个示例中,我们将`AuthGuard`守卫添加到`/`和`/dashboard`路由中。这意味着只有在用户已登录的情况下才能访问这些路由。
希望这个示例可以帮助您开始使用Vue 2编写登录校验模块。