vue params、query傳參使用


聲明式:<router-link :to="...">
編程式:router.push(...)

這兩種方式 都可以實現跳轉鏈接,在上篇文章繼續,通過A組件跳轉鏈接到B組件並且傳參數。

1、router.push使用

  router/index.js

復制代碼
export default new Router({
  routes: [
     {
      path: '/',
      name: 'A',
      component: require('../components/A')
    },
    {
      path: '/B/:name/:age',
      name: 'B',
      component: require('../components/B')
    }
  ]
})
復制代碼

 

上邊,在路由中為B組件添加兩個參數 name ,age 

 

A組件,綁定一個@click事件,跳轉B組件傳參 使用params

復制代碼
<template>
  <div>  <!---只允許有一個最外層標簽 !-->
    <div>
      <p>{{message}}</p>
      <p @click="toBFun">跳轉B組件啊啊</p>
      <!--<router-link :to="{ path: '/B',params:{name:'zs',age:22}}">跳轉B組件啊啊</router-link>-->
    </div>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        message: 'vue好帥啊!'
      }
    },
    methods: {
      toBFun: function(){
        this.$router.push({name:'B',params:{name:'xy',age:22}});
      }
    }
  }
</script>
<style>

</style>
復制代碼

這時瀏覽器會顯示 :

http://localhost:8080/#/B/xy/22

 

在看下query  傳值及地址變化

同樣在 router/index.js路由文件中 不變有兩個參數name,age

 {
      path: '/B/:name/:age',
      name: 'B',
      component: require('../components/B')
    }

 

在A組件中,之前參數傳遞是通過params,

this.$router.push({name:'B',params:{name:'xy',age:22}});

替換后,query

 this.$router.push({name:'B',query:{name:'xy',age:22}});

這時瀏覽器會發現:

http://localhost:8080/#/?name=xy&age=22

 

通過以上兩種,頁面刷新后,參數還會保留的。

獲取值有些不相同:

params:this.$route.params.name;
query:this.$route.query.name;

 

------------------------ 還有種方式--------------------------------------------

 使用 router-link

  <router-link :to="{ path: '/B',query:{name:'張飛',age:22}}">跳轉B組件</router-link>

跳轉后,瀏覽器地址為:

http://localhost:8080/#/B?name=zzz&age=22

跟  

this.$router.push(...) 是一樣的

 

 

-----------

  <router-link :to="{path:'/B/123'}">
        跳轉B組件</router-link>
    </div>

 

{
      path: '/B/:name',
      name: 'B',
      component: require('../components/B')
    }

取值

this.$route.params.name


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM