用vue2+vant生成一个登录拦截
时间: 2024-03-17 13:44:31 浏览: 20
好的,以下是使用 Vue2 和 Vant 实现登录拦截的基本步骤:
1. 安装 VantUI 组件库:在终端中输入 `npm install vant -S` 或者 `yarn add vant` 进行安装。
2. 在 main.js 中引入 VantUI 组件库:`import Vant from 'vant'`,并使用 `Vue.use(Vant)` 进行注册。
3. 在路由配置中定义需要登录才能访问的路由,例如:
```
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/profile',
name: 'profile',
component: Profile,
meta: {
requiresAuth: true
}
}
]
```
在上述代码中,我们定义了 `/profile` 路由需要登录后才能访问,因此我们需要在 meta 中添加 `requiresAuth: true` 属性。
4. 在路由守卫中进行登录拦截,例如:
```
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
```
在上述代码中,我们使用 `to.matched.some(record => record.meta.requiresAuth)` 判断当前路由是否需要登录,如果需要,则使用 `isAuthenticated()` 判断用户是否已经登录,如果已经登录,则放行,否则跳转到登录页面。
5. 在登录页面中进行登录操作,例如:
```
<template>
<div>
<van-field v-model="username" label="用户名"></van-field>
<van-field v-model="password" label="密码" type="password"></van-field>
<van-button type="primary" @click="login">登录</van-button>
</div>
</template>
<script>
export default {
data () {
return {
username: '',
password: ''
}
},
methods: {
login () {
// TODO: 进行登录操作
if (this.username === 'admin' && this.password === '123456') {
localStorage.setItem('isAuthenticated', true)
this.$router.push(this.$route.query.redirect || '/')
} else {
this.$toast.fail('用户名或密码错误')
}
}
}
}
</script>
```
在上述代码中,我们在 login 方法中进行登录操作,如果登录成功,则将 isAuthenticated 存储到 localStorage 中,并跳转到之前访问的路由或首页,否则提示用户用户名或密码错误。
6. 在 App.vue 中实现判断用户是否已经登录的方法,例如:
```
<script>
export default {
created () {
if (!isAuthenticated() && this.$route.meta.requiresAuth) {
this.$router.replace('/login')
}
}
}
</script>
```
在上述代码中,我们在 created 钩子函数中判断用户是否已经登录,如果没有登录且当前路由需要登录,则跳转到登录页面。
最后,我们需要实现 isAuthenticated 方法来判断用户是否登录:
```
function isAuthenticated () {
return localStorage.getItem('isAuthenticated') === 'true'
}
```
以上就是使用 Vue2 和 VantUI 实现登录拦截的基本步骤,可以根据实际需求进行修改和优化。