vue-router 路由2|青训营

64 阅读1分钟

1、路由的props配置

作用: 让路由组件更方便的收到参数

{
        name:'xiangqing',
        path:'detail/:id/:title',//detail是路由,后面两个是占位符,传入:id,title
        component:Detail,
        // props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件
        // props:{
        //     a:1,
        //     b:'hello'
        // }
        // props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以propsDetail组件
        // props:true
        // props的第三种写法,值为函数
        props($route){
            return {
                id: $route.query.id,
                title: $route.query.title
            }
        }
    }


获取参数,在对应的组件 :

props:['id','title'],

2、 的replace属性

作用:控制路由跳转时操作浏览器历史记录的模式 浏览器的历史纪录有两种写入方式,分别是push和replace,push是追加历史记录(类似与栈的数据进入和出去);replace是替换当前记录(只是替换一条记录,前面的记录不影响);路由跳转的时候默认为push

如何开启replace模式:

<router-link :replace='true' ……>About</router-link>或者 <router-link replace ……>About</router-link>

3、 编程式路由导航

作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活

具体编码----this.$router.push({……})和this.$router.replace({……})
methods:{
   pushShow(m){
      // console.log(this.$router)
      this.$router.push({
         name:'xiangqing',
         query:{
             id:m.id,
             title:m.title
         }
       })
    },
    replaceShow(m){
       this.$router.replace({
           name:'xiangqing',
           query:{
               id:m.id,
               title:m.title
            }
         })
     }
}
    

前进和后退

前进:this.$router.forward()

后退:this.$router.back() 前进或者后退(传入参数的值为正还是负):this.$router.go(2)