要求:
业务逻辑实现:当用户访问其他页面时,如果是没有完成登录的用户将限制访问,并跳转回登录页面 ,如果是完成登录的用户将可以访问任意页面。
效果图:
indec.js
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
// import LoginUser from '../views/LoginUser.vue'
// 许莉209010328
const routes = [
// 首页
{
path: '/',
name: 'home',
component: HomeView
},
// 关于我们
{
path: '/about',
name: 'about',
meta:{requireAuth:true},
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
},
// 登录界面
{
path: '/loginUser',
name: 'loginUser',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/LoginUser.vue')
// component:LoginUser
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
// 导航守卫
router.beforeEach((to)=>{
let userToken = window.localStorage.getItem('userToken')
if(to.name != 'loginUser' && userToken ==null){
return false;
}
})
export default router
AboutView.vue
<template>
<div class="about">
<h1>这是关于我们的介绍</h1>
</div>
</template>
HomeView.vue
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<h1>欢迎来到我们的首页</h1>
</div>
</template>
<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
// components: {
// HelloWorld
// }
}
</script>
LoginUser.vue
<template>
<div>
<!-- 209010328许莉 -->
<!-- 登录表单 -->
<from>
<h1>用户登录</h1>
<p>用户名:<input type="text" placeholder="请输入用户名" v-model="username"></p>
<p>密 码:<input type="password" placeholder="请输入密码" v-model="password"></p>
<button @click="submit">登录</button>
</from>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const username = ref("")
const password = ref()
let submit = ref()
// const query = ref()
const router = useRouter()
const route = useRoute()
//验证密码
submit=()=>{
if(username.value ==='qiqi'&& password.value ==='123456'){
window.localStorage.setItem('userToken',
username.value+password.value)
router.push('/')
}else{
alert('用户名和密码不能为空!')
}
}
console.log(route)
</script>
<style lang='scss' scoped>
</style>
App.vue
<template>
<!-- 209010328许莉 -->
<nav>
<router-link to="/">首页</router-link> |
<router-link to="/about">关于我们</router-link>|
<router-link to="/loginuser">用户登录</router-link>
</nav>
<router-view/>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>