溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue路由傳值的方式有哪些

發(fā)布時間:2021-09-14 12:14:38 來源:億速云 閱讀:182 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)vue路由傳值的方式有哪些的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

vue路由傳值的方式:1、利用“router-link”路由導(dǎo)航來傳遞;2、調(diào)用“$router.push”實現(xiàn)路由傳參數(shù)值;3、通過路由屬性中的name匹配路由,再根據(jù)params傳遞參數(shù)值;4、通過query來傳遞參數(shù)值。

本教程操作環(huán)境:windows7系統(tǒng)、vue2.9.6版,DELL G3電腦。

vue路由傳參值的方法

一、router-link路由導(dǎo)航

父組件: 使用<router-link to = "/跳轉(zhuǎn)路徑/傳入的參數(shù)"></router-link>

例如:<router-link to="/a/123">routerlink傳參</router-link>

子組件: this.$route.params.num接收父組件傳遞過來的參數(shù)

mounted () {
  this.num = this.$route.params.num
}

路由配置:{path: '/a/:num', name: A, component: A}

地址欄中的顯示:http://localhost:8080/#/a/123

二、調(diào)用$router.push實現(xiàn)路由傳參

父組件: 綁定點擊事件,編寫跳轉(zhuǎn)代碼

<button @click="deliverParams(123)">push傳參</button>
  methods: {
    deliverParams (id) {
      this.$router.push({
        path: `/d/${id}`
      })
    }
  }

子組件: this.$route.params.id接收父組件傳遞過來的參數(shù)

mounted () {
  this.id = this.$route.params.id
}

路由配置:{path: '/d/:id', name: D, component: D}

地址欄中的顯示:http://localhost:8080/#/d/123

三、通過路由屬性中的name匹配路由,再根據(jù)params傳遞參數(shù)

父組件: 匹配路由配置好的屬性名

<button @click="deliverByName()">params傳參</button>
    deliverByName () {
      this.$router.push({
        name: 'B',
        params: {
          sometext: '一只羊出沒'
        }
      })
    }

子組件:

<template>
  <div id="b">
    This is page B!
    <p>傳入?yún)?shù):{{this.$route.params.sometext}}</p>
  </div>
</template>

路由配置: 路徑后面不需要再加傳入的參數(shù),但是name必須和父組件中的name一致
{path: '/b', name: 'B', component: B}

地址欄中的顯示: 可以看出地址欄不會帶有傳入的參數(shù),且再次刷新頁面后參數(shù)會丟失
http://localhost:8080/#/b

四、通過query來傳遞參數(shù)

父組件:

<button @click="deliverQuery()">query傳參</button>
    deliverQuery () {
      this.$router.push({
        path: '/c',
        query: {
          sometext: '這是小羊同學(xué)'
        }
      })
    }

子組件:

<template>
  <div id="C">
    This is page C!
    <p>這是父組件傳入的數(shù)據(jù): {{this.$route.query.sometext}}</p>
  </div>
</template>

路由配置: 不需要做任何修改
{path: '/c', name: 'C', component: C}

地址欄中的顯示: (中文做了轉(zhuǎn)碼)
http://localhost:8080/#/c?sometext=%E8%BF%99%E6%98%AF%E5%B0%8F%E7%BE%8A%E5%90%8C%E5%AD%A6

感謝各位的閱讀!關(guān)于“vue路由傳值的方式有哪些”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI