安装vue
npm install -g @vue/cli //安装一次就可以
vue create 项目名称
cd 项目名称
npm run serve
配置 vue.config.js (关闭保存代码错误提示)
module.exports = {
lintOnSave: false
}
安装vue-router(路由)
npm install vue-router --save
使用
路由注册
重定向
动态二级路由
命名路由
全局路由配置
路由模式:hash history
import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '@/views/Films'
import Cinames from '@/views/Cinames'
import Center from '@/views/Center'
import nowplaying from '@/views/films/Nowplaying'
import comingsoon from '@/views/films/Comingsoon'
import search from '@/views/Search'
// 注册路由插件
Vue.use(VueRouter)
// 配置表
const routes = [
{
path: '/films',
component: Films,
children: [
{
path: '/films/nowplaying',
component: nowplaying
},
{
path: '/films/comingsoon',
component: comingsoon
},
// 再次重定向
{
path: '/films',
redirect: '/films/nowplaying'
}
]
},
{
name: 'kerwinDetail', // 命名路由
path: '/detail/:myid', // 动态二级路由
component: () => import('@/views/Detail')
},
{
path: '/cinames',
component: Cinames
},
{
path: '/cinames/search',
component: search
},
{
path: '/center',
component: Center,
// 通过判断是否放行
meta: {
isRequired: true
}
},
{
path: '/login',
component: () => import('@/views/Login')
},
// 重定向
{
// path: '/'
path: '*',
redirect: '/films'
}
]
const router = new VueRouter({
mode: 'hash',
routes
})
// 全局路由拦截(守卫)
router.beforeEach((to, from, next) => {
console.log(to.fullPath)
// 第一个方法
// if (to.fullPath === '/center') {
if (to.meta.isRequired) {
// 判断本地是否存储token
if (localStorage.getItem('token')) {
next()
} else {
// next('/login')
next({
// 跳转失败,到登录界面
path: '/login',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
})
export default router