关于路由vue-router

1、基础用法

下载vue-router:

npm install vue-router --save
或者使用淘宝镜像下载:
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install vue-router --save

在main.js中引入:

import router from './router'

Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

在router文件夹的index.js中:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
	  { 
	    path:'/', 
	    redirect:'/login'      //重定向,项目启动首页为登录页
	  },
	  { 
	    path:'/login', 
	    component:()=>import('@/components/login.vue'),
	  },
	  { 
	    path:'/home', 
	    component:()=>import('@/components/home.vue'),
	    redirect:'/welcome',
	    //home页面中的子路由,代替home页面中的<router-view>
	    children:[
	      {
	        path:'/welcome',
	        component:()=>import('@/components/welcome.vue')
	      },
	      {
	        path:'/users',
	        component:()=>import('@/components/users/users.vue')
	      },
	      {
	        path:'/rights',
	        component:()=>import('@/components/authority/rights.vue')
	      }
	    ]
	  }
]

const router = new VueRouter({
  	routes
})

export default router

2、解决重复点击路由出现的错误

报错信息:Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/video”.

解决办法:
在router文件夹下的index.js文件中添加:

// 解决重复点击路由出现的错误 this.$router.push()
  //下面的 VueRouter 是 import VueRouter from 'vue-router' 引入的
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

3、路由导航守卫

常用于:如果用户没有进行登录,就不可以查看其它页面的信息

在router文件夹的index.js中:

// 全局前置守卫
router.beforeEach((to, from, next)=>{
  // to : 要去的路由
  // from : 从哪个路由过来的
  // next : 是一个函数,表示放行
  // next()  放行     next('/login)  强制跳转到login路由
   if (to.path === '/login') return next()  
  const token = window.sessionStorage.getItem('token')    //  获取token
  if (!token)  {  // 如果没有token,就只能放行登录页面
    return next('/login')
  }
  next()
})


其他路由守卫:在具体某个页面中使用

<script>
    export default {
        name:'opinion',
        data(){
            return {  }
        },
        methods:{ 
        
        },
        //局部路由守卫(在某个页面使用)
        beforeRouterEnter( to, from ,next){ 

		}
        
    }
</script>

4、传参

1、简单数据

传参:
在这里插入图片描述在这里插入图片描述
接参:
在这里插入图片描述
2、复杂数据

传参:

<router-link :to="{path:'/finance/detail/sub-detail',query: {id: "5000"}}">跳转</router-link>

接参:

this.$route.query.id

3、如果不需要传参
如果从其他页面调过来不需要传参,但是需要在路由后边加上形参,不然跳转过来页面就会空白

<router-link :to="/finance/detail/sub-detail/:id'">跳转</router-link>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值