Vue Router 相关文章
# Vue Router 全面详解--【一、基础篇,从零开始搭建Vue Router】
接着上一篇,假如现在我们有个需求,未登录的用户只能进入首页和登录页面,该该怎么做呢? 这个时候就需要用到Vue Router 的路由守卫了。
一、 我们先来新建一个Login 页面吧, 具体代码如下
<template>
<div class="login-wraper">
<p>登录</p>
<div class="login-input">
<label>用户名:</label>
<input v-model="userName"/>
</div>
<div class="login-input">
<label>密码:</label>
<input type="password" v-model="password" />
</div>
<button @click="login" class="login-button">登录</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useCookies } from 'vue3-cookies'
const { cookies } = useCookies()
const userName = ref('')
const password = ref('')
function login () {
cookies.set('username', userName.value)
cookies.set('password', password.value)
alert('登录成功')
}
</script>
<style scoped>
.login-wraper {
margin: 0 auto;
width: 400px;
}
.login-input{
display: flex;
align-items: center;
margin-bottom: 20px;
}
.login-input label{
width: 120px;
}
.login-input input {
line-height: 36px;
border: 1px solid #ddd;
border-radius: 5px;
}
.login-button {
background: #296dff;
color: #fff;
}
</style>
设置cookie 模拟登录,
路由表增加 Login
{
path: '/login',
name: "Login",
component: Login
},
登录页面相关开发完成,接下来利用vue-router 的路由守卫进行权限判断,在此之前,先要介绍一个东西meta, 路由源,可以利用meta 配置权限选项, meta是一个对象,我们增加一个auth选项, 值为0和1, 0表示不需要登录就可以访问,1表示必须要登录。除了登录页面和首页,其他页面都需要登录,所以路由列表配置如下:
const routes = [
{
path: '/',
name: "Index",
component: Index,
meta: {
auth: 0,
}
},
{
path: '/login',
name: "Login",
component: Login,
meta: {
auth: 0,
}
},
{
path: '/newlist',
name: "NewList",
component: NewList,
meta: {
auth: 1,
}
},
{
path: '/new-detail/:id',
name: "NewDetail",
component: NewDetail,
meta: {
auth: 1,
}
},
{
path: '/article-list',
name: "ArticleList",
component: ArticleList,
meta: {
auth: 1,
}
},
{
path: '/article-detail/:id',
name: "ArticleLDetail",
component: ArticleLDetail,
meta: {
auth: 1,
}
}
]
再接下来就是文章的重点了, 路由守卫,这里首先要介绍的是beforeEach 全局的路由前置守卫。他接收一个回调函数,这个回调函数有三个参数,to, from, next, to 要进入到的页面的相关信息, from 进入新页面之前的页面的信息。next 执行下一步。
这里我们就通过to 里面获取到meta 里面的auth 权限配置信息。通过auth 我们就可以拦截。如果没登录跳转到新闻或者文章相关页面,我们则让他跳转到登录页面登录。 具体实现代码如下:
const { cookies } = useCookies()
router.beforeEach(function (to, from, next) {
if(cookies.get('username')) { // 已经登录直接跳转
next()
} else {
if (to.meta.auth === 1) { // 没登陆,但是进入了需要登录的页面
alert('需要登录权限')
next({ name: 'Login'})
} else {
next() // 进入不需要登录的页面
}
}
})
来试下效果,现在还没登录,我们访问下首页
正常访问。
来点击下新闻或者文章呢!这时候你就会看到一个弹框提示。
点击确定之后,就跳转到了登录页面,我们来登录下。
点击登录,弹出了登录成功
现在我们再来点击下文章和新闻,发现可以正常进入了。
点击列表进入文章详情,一样能正常进入
一个简单的登录权限功能就开发完成了,感谢收看
Vue Router 相关文章