vue-router学习总结

2019-07-24  本文已影响0人  牛妈代代

1.引入vue-router

npm install vue-router --save

2.设置路由
(1)路由实例常见属性设置:

export default new Router({
    mode:"hash" | "history" | "abstract"       //路由模式,默认值"hash"  
    base:string   //应用的基路径,默认值"/"  
    linkActiveClass:string   //激活 class 类名,默认值"router-link-active"  
    linkExactActiveClass:string   //精确激活的默认的 class,默认值"router-link-exact-active"  
    scrollBehavior:Function   //滚动行为  
    parseQuery / stringifyQuery:Function  //提供自定义查询字符串的解析/反解析函数  
    fallback:boolean   //当浏览器不支持 history.pushState 控制路由是否应该回退到 hash 模式  
    routes:[]        //构建路由
})

(2)routes:[]构建路由

routes:[{
    path:string,     //定义路径
    component:Component,   //声明组件
    name:string,        //命名路由
    components:{default:component,name:component},  //命名多组件
    redirect:string|location|fun,    //路由重定位
    props?: boolean | Object | Function; //将组件和路由解耦
    alias:string|Array,     //别名
    childer:{},              //路由嵌套
    beforeEnter:(to: Route, from: Route, next: Function) => void,
    meta:any,     //元数据。在meta对象中可以设置一些状态,来进行一些操作;
    //2.6.0+版本新增
    caseSensitive:bloolean,    //匹配大小写敏感,默认flase
    pathToRegexpOptions:object          //编译正则选项

}]

3.页面应用
<router-link></router-link>:路由导航,默认渲染成<a>标签

<router-link to="/home" replace tat="li" active-class="active" ></router-link>
<router-link :to="{ name:'router1',params: { id: status}}" ></router-link>
<router-view></router-view>   //渲染路径匹配到的视图组件  

to:string | Location #目标路由的链接
replace:boolean # 是否留下 history 记录,默认值false
append:boolean # 是否为相对路径,默认值false
tag:string # 渲染指定标签,默认值<a>标签
active-class:string # 链接激活样式,默认值"router-link-active"
exact:boolean # 是否精准匹配,默认值false
event:string | Array<string> # 触发导航的事件,默认值'click'
exact-active-class: string # 精准匹配激活样式,默认值'router-link-exact-active'

4.$router全局路由对象
实例属性
router.app: Vue instance #Vue 根实例
router.mode: string #路由使用的模式
router.currentRoute: Route #当前路由对应的路由信息对象

动态的导航到一个新 URL
router.push(location, onComplete?, onAbort?)
router.replace(location, onComplete?, onAbort?)
router.go(n) //n=0为刷新,n>0为前进,n<0为后退
router.back() //后退
router.forward() //向前;

增加全局的导航守卫
router.beforeEach((to, from, next) => { /* must call next / })
router.beforeResolve((to, from, next) => { /
must call next */ })
router.afterEach((to, from) => {})

router.getMatchedComponents(location?) //返回目标位置或是当前路由匹配的组件数组
router.resolve(location, current?, append?) //解析目标位置
router.addRoutes(routes: Array<RouteConfig>) //动态添加更多的路由规则
router.onReady(callback, [errorCallback]) // 回调函数,路由完成初始导航时调用
router.onError(callback) //回调函数,路由导航过程中出错时被调用

5.$route实例化路由对象
路由对象属性
$route.path: string //当前路由的路径,总是解析为绝对路径
$route.params: Object //包含了动态片段和全匹配片段
$route.query: Object //表示 URL 查询参数
$route.hash: string //当前路由的 hash 值
$route.fullPath: string //完成解析后的 URL
$route.matched: Array<RouteRecord> //当前路由的所有嵌套路径片段的路由记录
$route.name //当前路由的名称
$route.redirectedFrom //重定向来源的路由的名字

上一篇下一篇

猜你喜欢

热点阅读