Vue-router重修02

时间:2022-02-14 17:35:37

1、权限控制

例如:登录后登录前的页面不一样

借助路由元信息完成

一个示例:

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
</head> <body>
<div id="app">
<!-- 声明式导航 -->
<router-link to="/home">首页</router-link>
<router-link to="/blog">我的博客</router-link>
<router-link to="/login">登录</router-link>
<!-- <router-link to="/blog">退出</router-link> -->
<a href="javascript:void(0)" @click="clear">退出</a>
<router-view></router-view>
</div>
</body> <script>
Vue.use(VueRouter) let Home = {
template: '<h1>首页内容</h1>'
} let Blog = {
template: '<h1>博客页内容</h1>'
} let Login = {
template: `<div>
<input type="text" v-model="name">
<input type="text" v-model="pwd">
<input type="button" value="登录" @click="login">
</div>`,
data() {
return {
name: '',
pwd: ''
}
},
methods: {
login() {
localStorage.setItem('user', this.name)
//利用编程式导航实现登陆后跳转
this.$router.push({name:'blog'})
}
}
} var router = new VueRouter({
routes: [
{
path: '/home',
component: Home
},
{
path: '/',
redirect: 'home'
},
{
path: '/blog',
component: Blog,
name:'blog',
//为未来的路由作权限控制 全局路由守卫作参照条件
meta: {
//若auth为true,则用户访问该组件时需要登录
auth: true
}
},
{
path: '/login',
component: Login
}
]
}) router.beforeEach((to, from, next) => {
if (to.meta.auth) {
if (localStorage.getItem('user')) {
next()//已有登录状态,放行
} else {//需要登录
next({ path: '/login' })//未登录,利用next重定向至登录组件
}
} else {
next()//放行
}
}) new Vue({
el: '#app',
router,
methods:{
clear(){
localStorage.removeItem('user')
this.$router.push('/login')
}
}
}) </script> </html>

2、keep-alive

1)

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
</head> <body>
<div id="app"> </div>
</body>
<script>
Vue.use(VueRouter)
let Series = {
template: `<div>付费栏目</div>`
}
let Topics = {
template: `<div>砖头广场</div>`
} let App = {//keep-alive将组件状态放至缓存中保存起来
template: `<div>
<router-link to="/series">付费栏目</router-link>
<router-link to="/topics">砖头广场</router-link>
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>`
} let router=new VueRouter({
routes:[
{path:'/series',component:Series},
{path:'/topics',component:Topics},
]
})
new Vue({
el: '#app',
template: `<App />`,
components: {
App
},
router
})
</script> </html>