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' Vue.use(VueRouter)
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: '/' }
]
const router = new VueRouter({mode: 'history',routes,scrollBehavior(to, from, savedPosition) {return {x: 0,y: to.meta.scrollTop || 0}; }
})export default router;
./src/App.vue入口组件与其它组件内
-
(主要功能是进行本地路由跳转)
- to="/XX" :本地路由跳转到 “/XX”
- tag=“button” :此组件被渲染成"button"标签
- replace :replace不留下history路由记录,不能访问上一级
- active-class =“router-link-active” 本组件活跃时附加的class类名
-
(路由跳转对应组件的渲染位置)
-
vue有几种路由? (保持路由跳转使用过的组件的活性)
- 组件的vue实例内(组件被包裹时,activated和deactivated函数被允许使用)
- activated(){//被保持活性时调用}
- deactivated(){//不再被保持活性时调用}
- include=“组件vue实例的name属性值,name1,name2” //允许保持活性的组件名
- exclude=“组件vue实例的name属性值,name1,name2” //不允许保持活性的组件名
-
所有组件的内(所有的组件都继承vue类,vue.prototype.$router = ()=>{import router from “./router/index.js” ); return router; }
- this.$router (./src/router/index.js导出的router容器对象被全局挂载到vue实例上了)
- this.$router.push("/XX") :本地路由跳转到"/XX",保存路由记录
- this.$router.replace("/XX") :本地路由跳转到"/XX",不作路由记录
- this.$route (./src/router/index.js导出的router容器对象中的当前活跃路由被全局挂载到vue实例上了)
- this.$route.params.x1可以读取到x1被赋值的内容
- this.$route.query.x1可以读取到组件传给路由的参数
组件与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”}})
- 其它组件内
@沉木