vue 路由与路由守卫

添加路由

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Detail from '../views/Detail.vue'
Vue.use(VueRouter)
  const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/detail',
    name: 'Detail',
    component: Detail
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
]
const router = new VueRouter({
  routes
})
export default router

路由跳转

使用<router-link to="path路径"></router-link>进行路由跳转

使用<router-view></router-view>进行显示

路由重定向

使用redirect进行路由的重定向

  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect:'/detail'
  },
  {
    path: '/detail',
    name: 'Detail',
    component: Detail,
    
  },

定义子路由

 {
    path: '/detail',
    name: 'Detail',
    component: Detail,
    children:[
    	{
    	 	path: 'info',
    	 	//以"/"开头的嵌套路径会被当作根路径,所以子路由上不用加"/";
    	 	 name: 'Info',
    		component: Info,
    	},
    ]
  },

路由传参

  • 使用$router.push实现携带参数跳转
  • 可以使用this.$route.params.id获取参数
getDetail(id) {
        this.$router.push({
          path: `/detail/${id}`,
        })

路由配置

{
     path: '/detail/:id',
     name: 'Detail',
     component: Detail
   }
  • 通过name值来确定路由,通过params进行传值
this.$router.push({
          name: 'Detail',
          params: {id: id}
        })
  • 通过path匹配路由,通过query进行传值
this.$router.push({
          path: '/Detail',
          query: {
            id: id
          }
        })

路由守卫

router.beforeEach((to, from, next) => {
  //to 前往的路由, from 来的路由, next 下一步钩子函数,没有问题,执行next() 
  console.log(to);
  if (to.path !== '/login') {
      if (window.isLogin) {
          next()
      } else {
          next('/login?redirect='+ to.path)
      }
  } else {
      next()
  }
})

猜你喜欢

转载自blog.csdn.net/hhhhhhhhhtr/article/details/106918493