vue2-router路由相关
Vue 2 中通常使用
1、npm install vue-router@3.x
版本(与 Vue 2 适配)来实现路由功能,它能帮助你构建单页应用(SPA),实现不同组件之间的无刷新切换
2、基本路由配置(src/router/index.js)
import Vue from 'vue' import VueRouter from 'vue-router' // 导入组件 import Home from '../components/Home.vue' import About from '../components/About.vue' // 注册路由插件 Vue.use(VueRouter) // 定义路由规则 const routes = [ { path: '/', // 路径 name: 'Home', // 路由名称(可选) component: Home // 对应组件 }, { path: '/about', name: 'About', component: About } ] // 创建路由实例 const router = new VueRouter({ mode: 'history', // 路由模式(history 无 # 号,hash 有 # 号) base: process.env.BASE_URL, // 基础路径 routes // 挂载路由规则 }) export default router
3、在入口文件中引入(src/main.js)
javascript 运行 import Vue from 'vue' import App from './App.vue' import router from './router' // 引入路由实例 new Vue({ router, // 注入路由,使所有组件可访问 $router 和 $route render: h => h(App) }).$mount('#app')
路由跳转与导航
this.$router.push({ name: 'About' })
this.$router.push({ path: 'About' })
this.$router.push({ path: 'About',query:{name:'zs'} }) 类似url?name=zs
取参数
针对query: this.$route.query.id
动态路由与路由参数 --获取时使用 watch监听 $route获取获取参数 or 组件内守卫 beforeRouteUpdate(to,from,next)监听数据变化
// router/index.js const routes = [ { path: '/user/:id', // :id 是动态参数 name: 'User', component: () => import('../components/User.vue') // 异步加载组件 } ]
获取: {{ $route.params.id }}
// 监听路由参数变化(同一组件复用,参数变化时触发)详情页面组件相同,id不同情况,页面不会重新渲染, watch: { '$route.params'(newParams) { console.log('参数变化:', newParams) } }
。。。
watch:{
$route:{
handler(newVal){
console.log('newVal')
},
immediate: true,
deep:true
}
}
配置嵌套路由 -层级展示需要
// router/index.js const routes = [ { path: '/home', name: 'Home', component: Home, // 子路由(children 数组) children: [ { path: 'news', // 子路径(注意不要加 /,最终路径为 /home/news) component: () => import('../components/HomeNews.vue') }, { path: 'message', // 最终路径 /home/message component: () => import('../components/HomeMessage.vue') } ] } ]
路由守卫(导航守卫)
// router/index.js router.beforeEach((to, from, next) => { // to: 要跳转到的路由 // from: 从哪个路由跳转过来 // next(): 必须调用,否则路由无法跳转 // 示例:判断是否登录,未登录拦截到登录页 if (to.path === '/admin' && !isLogin()) { next('/login') // 跳转到登录页 } else { next() // 允许跳转 } })
组件内守卫
<script> export default { // 进入组件前触发 beforeRouteEnter(to, from, next) { next(vm => { // 通过 vm 访问组件实例!!!!!!!!!!!!!!!!!!1 if (vm.checkPermission()) { next() } else { next(false) // 阻止进入 } }) }, // 组件内路由参数变化时触发 beforeRouteUpdate(to, from, next) { this.loadData(to.params.id) // 重新加载数据 next() }, // 离开组件时触发 beforeRouteLeave(to, from, next) { if (confirm('确定要离开吗?')) { next() } else { next(false) // 阻止离开 } } } </script>
路由模式
常见问题
浙公网安备 33010602011771号