命名路由 router-link ,动态获取数据的方法 this.$route ,编程导航 this.$router

边浩漫
2023-12-01

命名路由 router-link

相当于一个 a 标签,也有点击跳转功能的。

  • 需求,通过a标签点击,做页面数据的跳转

  • app.vue 中使用router-link标签

    • 1:去哪里 <router-link to="/beijing">去北京</router-link>
    • 2:去哪里 <router-link :to="{name:'bj'}">去北京</router-link>
      • 更利于维护,如果修改了path,只修改路由配置中的path,该a标签会根据修改后的值生成href属性
  • main.js 中的路由对象中配置路由规则

    let router = new VueRouter({
        // 这里是多个路由的集合
        routes : [
            {name : "music",path : "/music/:id" , component : Music},
            { path: '/movie', component: Movie }
        ]
    })
    // 别的vue文件中引用了之后,后续要修改只需要修改main.js中的内容。
    # 假设在 A 页面点击了一个英雄要跳转到该详情页,那么就得传参数给query字符串或者params。
     <router-link :to="{name : 'detail' , params : {id : index }}">查看</router-link>
    

router-link 获取数据 this.$route

获取数据的属性方法。

给 router-link 添加全局的自定义样式时,要注意:

// main.js 中 linkActiveClass 要放在 routes 之前,否则没效果
linkActiveClass : "mui-active",
1.传递参数的vue文件中:<router-link>对象中设置把数据传到url中  
 <router-link :to="{name : 'detail' , params : {id : index }}">查看</router-link>
2.把属性挂载到main.js的routes中 
{name : "list",path : "/list/:id" , component : List}
3.在想要获得参数的地方:
  数据初始化的地方 created,mounted是dom已经加载完成要操作dom。所以数据的操作要在created中。
this.$route.query.id 或  this.$route.params.id
  • 在vue-router中,有两大对象被挂载到了实例this

    • $route 只读、具备信息的对象
    • $router 具备功能函数
  • 查询字符串

    得到的 url 链接http://localhost:8080/#/movie?id=1&name=2

    • 1: list.vue 中去哪里 <router-link :to="{name:'detail',query:{id:1} } ">xxx</router-link>
    • 2: main.js 中导航(查询字符串path不用改) { name:'detail' , path:'/detail',组件}
      • 信息是挂载到了 Vue.use(VueRouter) 中
    • 3:detail.vue 中获取路由参数(要注意是query还是params和对应id名)
      • this.$route.query.id
  • path方式

    得到的 url 链接 http://localhost:8080/#/movie/2

    • 1: list.vue 中去哪里 <router-link :to="{name:'detail',params:{name:1} } ">xxx</router-link>

    • 2: main.js 中导航(path方式需要在路由规则上加上 /:xxx)

      let router = new VueRouter({
      	{ name:'detail' , path:'/detail/:name',组件}
       })
      
    • 3: detail.vue 中获取路由参数(要注意是query还是params和对应name名)

      • this.$route.params.name

编程导航 this.$router

就是像浏览器一样有前进,后退,或者是跳转到某一页的功能。

  • 不能保证用户一定会点击某些按钮

  • 并且当前操作,除了路由跳转以外,还有一些别的附加操作

  • this.$router.go 根据浏览器记录 前进1 后退-1

     goBack(){
         this.$router.go(-1)
     }
    
  • this.$router.push(直接跳转到某个页面显示)

    • push参数: 字符串 /xxx this.$router.push("/")
    • 对象 : {name:'xxx',query:{id:1},params:{name:2} }
goMovie(){
	 this.$router.push({
          name : "movie",
          query : { id : 1,name :2}  //得到的url参数为http://localhost:8080/#/movie?id=1&name=2
        query : { id : 1},params : {name :2}   //http://localhost:8080/#/movie2?id=1
     })
}
 类似资料: