美文网首页
vue-router编程式路由

vue-router编程式路由

作者: tutututudou | 来源:发表于2022-06-24 00:00 被阅读0次

    让图片、按钮都可以点击跳转,使用$router这个API

    每个组件都能看到$router这个API的

    在button、图片添加点击事件,点击事件里调用$router这个API

    <ul>
        <li v-for="m in msg" :key="m.id">
        <button @click="hanlderPush(m)">push</button>
        <button @click="handlerReplace(m)">replace</button>
        </li>
       </ul>
    
    methods:{
       // m是for循环的msg的值 v-for="m in msg",是实参,hanlderPush(x),x是形参
       hanlderPush(x){
        //  路由命名方式
        // this.$router.push这个就相当于<router-link :to="{name:'detail',params:{x:m.id,y:m.title}}">
        // 只不过这是写在button事件里,其它的标签也可以写成事件的方式进行跳转
        //{}里面的都和to一样的规则写法
         this.$router.push({ path:'/home/message/detail', query:{id:x.id,title:x.title}})
        //  http://localhost:8080/#/home/message/detail?id=004&title=%E6%B6%88%E6%81%AF4
       },
       handlerReplace(y){
        //  this.$router.replace也可进行跳转,指定跳到哪个路由组件,携带query参数
         this.$router.replace({name:'detail',query:{id:y.id,title:y.title}})
       }
     }
    
    • 前进 后退 定点步数
       <button @click="forward">前进</button>
        <button @click="back">后退</button>
        <button @click="go">定点步数</button>
    ...
      methods:{
        // 和浏览器的前进后台历史记录的按钮一样功能
        forward(){
          this.$router.forward()
        },
        back(){
          this.$router.back()
        },
        // 可以自定义跳转几步,正数是前进,复数是后台
        go(){
          //前进2步
          // this.$router.go(1)
          //后台2步
          this.$router.go(-1)
        }
      },
    

    这个是replace可以应用在无痕浏览

    相关文章

      网友评论

          本文标题:vue-router编程式路由

          本文链接:https://www.haomeiwen.com/subject/wvhodrtx.html