vue路由的使用

安装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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值