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>