动态路由
1.编写点击跳转页面的逻辑(编程式导航、传参)
//===>src/views/Film/Nowplaying.vue
<template>
<div>
nowplaying
<ul>
<li v-for="data in datalist" :key="data" @click="handleChangePage(data)">{{data}}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
datalist: ["1111", "2222", "3333"]
};
},
methods: {
handleChangePage(id) {
console.log(id);
//编程式导航
this.$router.push(`/detail/${id}`);
}
}
};
</script>
2.编写detail页面的跳转规则
//===>src/router/index.js
...
import Detail from '@/views/Film/Detail'
Vue.use(VueRouter)
const routes = [
{
path: '/film',
...
]
},
...
{
path: '/detail/:id',
component: Detail
},
...
]
...
3.编写新的页面
//===>src/views/Film/Detail.vue
<template>
<div>detail</div>
</template>
<script>
export default {
mounted() {
console.log("要id获取详情信息", this.$route.params.id);
}
};
</script>
点击
带参数的跳转
history模式
路由守卫
全局守卫
1.在路由文件配置全局守卫
//===>src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Film from '@/views/Film'
import Cinema from '@/views/Cinema'
import Center from '@/views/Center'
import Login from '@/views/Login'
import Nowplaying from '@/views/Film/Nowplaying'
import Comingsoon from '@/views/Film/Comingsoon'
import Detail from '@/views/Film/Detail'
Vue.use(VueRouter)
const auth = {
isLogin() {
return false
}
}
const routes = [
{
path: '/film',
component: Film,
children: [
{
path: 'nowplaying',
component: Nowplaying
}, {
path: 'comingsoon',
component: Comingsoon
}, {
path: '',
redirect: '/film/nowplaying'
}
]
},
{
path: '/cinema',
component: Cinema
},
{
path: '/detail/:id',
name: 'kerwindetail',
component: Detail
},
{
path: '/center',
component: Center
},
{
path: '/login',
component: Login
},
{
path: '*',
component: Film
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 全局守卫
router.beforeEach((to, from, next) => {
console.log("盘查");
if (to.path === '/center') {
if (auth.isLogin()) {
next()
} else {
next('/login')
}
} else {
next()
}
})
export default router
2.编写Login组件
//===>src/views/Login.vue
<template>
<div>
Login
</div>
</template>
image.png
局部守卫
1.注释掉全局守卫
//===>src/router/index.js
...
// 全局守卫
// router.beforeEach((to, from, next) => {
// console.log("盘查");
// if (to.path === '/center') {
// if (auth.isLogin()) {
// next()
// } else {
// next('/login')
// }
// } else {
// next()
// }
// })
...
2.在Center页面编写局部守卫
//===>src/views/Center.vue
<template>
<div>Center</div>
</template>
<script>
export default {
beforeRouteEnter(to, from, next) {
console.log("局部盘查");
if (false) {
next();
} else {
next("/login");
}
}
};
</script>
<style lang="sass" scoped>
</style>
运行结果和全局守卫一样。
网友评论