本文共 3127 字,大约阅读时间需要 10 分钟。
vue-router
安装vue-router
- 对应项目打开终端输入"npm install vue-router --save"
./src/router/index.js文件中的内容:
- redirect :重定向
- mode:“history” 模式改为"history"模式
- linkActiveClass:“router-link-active” (所有组件活跃时附加的class类名)
- 路由懒加载(对JS代码进行分包,用到时自动请求加载)
- const Home = ()=>import("…/components/Home.vue")
- 路由嵌套
- router模块某个路由内
- children:[{path:“news”,component:News},{path:"",redirect:“news”},{}]
- 父组件内
- 路由导航守卫(路由跳转中的一些操作)
- 全局导航守卫(router模块内)
- router.beforEach((to,from,next)=>{ document.title = to.matched[0].meta.title; next();});
- router.afterEach((to,from)=>{ console.log(“路由跳转完成”)});
- 路由独享守卫(router模块内的某个route内)
- {path:’/XX’,conponent:XX,beforEnter:(to,from,next)=>{…}}
- 组件内守卫(组件的vue实例中)
- {data(){return {…}}, beforeRouteEnter(to,from,next){//在渲染该组件的对应路由被confirm前调用}}
- {data(){return {…}}, beforeRouteUpdate(to,from,next){//当路由改变,但该组件被复用时调用}}
- {data(){return {…}}, beforeRouteLeave(to,from,next){//导航离开该组件的对应路由调用}}
- ./src/router/index.js文件实例:
import Vue from 'vue'import VueRouter from 'vue-router' //1,引入vue-router第三方模块Vue.use(VueRouter) //2,挂载中间件//3,配置路由映射表const routes = [{ path: '/fans-and-integral', name: '粉丝和积分', component: FansAndIntegral, meta: { title: '粉丝和积分' + mainTitle, iswechat: true } }, { path: '/login', redirect: '/' }, { path: '/home', redirect: '/' }, { path: '/auth', redirect: '/setting' }, { path: '*', // 此处需特别注意至于最底部 redirect: '/' // 临时重定向到主页 }]// 4,创建路由容器并设置相关配置const router = new VueRouter({ mode: 'history', routes, scrollBehavior(to, from, savedPosition) { // return { x: 0, y: 0 } return { x: 0, y: to.meta.scrollTop || 0 }; //进入该页面时,用之前保存的滚动位置赋值 }})export default router; // 5,导出路由容器,App.vue的vue实例上(new Vue({ router:router }))挂载路由容器/* 6,使用: 1,全局组件 2, 3, 4,this.$router.push("/")*/
./src/App.vue入口组件与其它组件内
组件与router/index.js之间的交互
- 动态路由(动态改下path内容)
- router模块内
- 对应组件内
- <router-link :to= “’/home/’+data1”></router-link>
- 其它组件内
- this.$route.params.x1可以读取到x1被赋值的内容
- 组件的参数传递给路由
- router模块内
- 对应组件内
- <router-link :to= “{ path:’/home’,query:{x1:‘XX’,x2:‘XX’,} }”></router-link>
- this.$router.push({path:"/home",query:{x1:“XX”,x2:“XX”}})
- 其它组件内
@沉木
转载地址:http://qhhgf.baihongyu.com/