学习vue——路由
一、配置vue2路由
vue2 router 版本3.6.5

router/index.js
1 import Vue from 'vue' 2 import VueRouter from 'vue-router' 3 import MyHeader from '@/components/MyHeader.vue' 4 import MyMain from '@/components/MyMain.vue' 5 6 Vue.use(VueRouter) 7 const router = new VueRouter({ 8 routes:[ 9 {path:'/page01/:name',component:MyHeader}, 10 {path:'/page02',component:MyMain} 11 ] 12 }) 13 14 15 export default router
main.js
1 import Vue from 'vue' 2 import App from './App.vue' 3 import router from './router' 4 5 Vue.config.productionTip = false 6 7 8 9 new Vue({ 10 render: h => h(App), 11 router 12 }).$mount('#app')
二、路由传参数



三、路由模式,带井号 和 不带井号

四、重定向、404
1 const router = new VueRouter({ 2 mode:'history', 3 routes:[ 4 {path:'/',redirect:'/page02'}, // 重定向 5 {path:'/page01/:name?',component:MyHeader}, 6 {path:'/page02',component:MyMain}, 7 // {path:'*',component:NotFund},// 配置404要放在最后面 8 ] 9 })
五、编程式路由

<button @click="tiao">点击跳转</button> methods:{ tiao(){ // this.$router.push("/page02") this.$router.push({ name:'pageName'
// 方法一:/page02?key=001
query:{
key:'001'
}
// 方法二:/page02/002,需要router/index.js里设置
parmars:{
name:'002'
}
})
}
}
router/index.js
{name:'pageName',path:'/page02/:name?',component:MyMain},
六、返回
<span @click="$router.back()">返回</span>
<span @click="$router.go(-1)">返回</span>
七、缓存路由
1、用法:冒号+include,后面跟的是组件name,
export default {
name:'xx'
}
2、一旦使用缓存,crated、motend、destor等钩子函数不能使用
3、被缓存组件,多了2个钩子,active、deactive


八、未登录,登录后返回原地址
// 如果希望,跳转到登录 => 登录后能回跳回来,需要在跳转去携带参数 (当前的路径地址)
// this.$route.fullPath (会包含查询参数)
this.$router.replace({
path: '/login',
query: {
backUrl: this.$route.fullPath
}
})
// 进行判断,看地址栏有无回跳地址
// 1. 如果有 => 说明是其他页面,拦截到登录来的,需要回跳
// 2. 如果没有 => 正常去首页
const url = this.$route.query.backUrl || '/'
this.$router.replace(url)

浙公网安备 33010602011771号