欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解vue?Router(v3.x)?路由傳參的三種方式

 更新時(shí)間:2023年07月17日 10:52:41   作者:C_心欲無痕  
vue路由傳參的使用場(chǎng)景一般都是應(yīng)用在父路由跳轉(zhuǎn)到子路由時(shí),攜帶參數(shù)跳轉(zhuǎn),本文將詳細(xì)介紹vue路由傳參的三種方式,這三種傳參方式只是針對(duì)vue?Router?V3版本的,需要的朋友可以參考下

前言

vue 路由傳參的使用場(chǎng)景一般都是應(yīng)用在父路由跳轉(zhuǎn)到子路由時(shí),攜帶參數(shù)跳轉(zhuǎn)。傳參方式可劃分為 params 傳參和 query 傳參,而 params 傳參又可分為在 url 中顯示參數(shù)和不顯示參數(shù)兩種方式,這就是vue路由傳參的三種方式。

當(dāng)然 ,這三種傳參方式只是針對(duì)vue Router V3版本的,V4版本的路由傳參會(huì)有些不同;V3版本經(jīng)常與vue2相配合使用;而V4版本則多和vue3配合使用;

一,params 傳參(顯示參數(shù))

這種方式vue router官網(wǎng)也叫 動(dòng)態(tài)路由匹配;

1,,首先需要在路由表中配置 冒號(hào)+參數(shù)(/user/:id

  	// 這是動(dòng)態(tài)路由 加上:/:id
      {
        path: "/routers/:id",
        name: "Routers",
        meta: { title: "動(dòng)態(tài)路由" },
        component: () => import("../views/routers/routers.vue")
      },

2,開始跳轉(zhuǎn)并傳參

jumpTo() {
      this.$router.push({ path: "/routers/123" });
    }

3,獲取動(dòng)態(tài)路由參數(shù)

created(){
	console.log('獲取', this.$route.params); //{id: '123'}
}

當(dāng)然,你也可以傳多個(gè)參數(shù),只不過需要在路由表中配置多個(gè),如下:

注意: 響應(yīng)路由參數(shù)的變化

注意:當(dāng)使用路由參數(shù)時(shí),例如從 /user/foo 導(dǎo)航到 /user/bar,原來的組件實(shí)例會(huì)被復(fù)用。因?yàn)閮蓚€(gè)路由都渲染同個(gè)組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會(huì)再被調(diào)用。

復(fù)用組件時(shí),想對(duì)路由參數(shù)的變化作出響應(yīng)的話,你可以簡(jiǎn)單地 watch (監(jiān)測(cè)變化) $route 對(duì)象:

const User = {
  template: '...',
  watch: {
    $route(to, from) {
      // 對(duì)路由變化作出響應(yīng)...
    }
  }
}

或者使用 2.2 中引入的 beforeRouteUpdate 導(dǎo)航守衛(wèi):

const User = {
  template: '...',
  beforeRouteUpdate(to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

二,params 傳參(不顯示參數(shù))

1,使用不顯示參數(shù)的方式,則不需要在進(jìn)行配置路由表:

  	{
        path: "routers",
        name: "Routers",
        component: () => import("../views/routers/routers.vue")
      },

2,開始跳轉(zhuǎn)并傳參

注意:需要指定路由表中的 name與之相對(duì)應(yīng);

jumpTo() {
      this.$router.push({ name: "Routers", params:{ id:123 } });
    }

3,獲取參數(shù)

this.$route.params.id

注意:上述這種利用 params 不顯示 url 傳參的方式會(huì)導(dǎo)致在刷新頁(yè)面的時(shí)候,傳遞的值會(huì)丟失;需要謹(jǐn)慎使用。

三,query 傳參(顯示參數(shù))

這種傳參方式會(huì)把你的參數(shù)以問號(hào)拼接到路由上面;刷新頁(yè)面且路由不會(huì)丟失。

1,這種也不需要進(jìn)行配置路由表:

  	{
        path: "routers",
        name: "Routers",
        component: () => import("../views/routers/routers.vue")
      },

2,開始跳轉(zhuǎn)并傳參

注意:需要與路由表中的 path屬性 與之相對(duì)應(yīng);

this.$router.push({ path:'/routers',  query:{	id:123 } })

3,獲取參數(shù)

this.$route.query.id

到此這篇關(guān)于詳解vue Router(v3.x) 路由傳參的三種方式的文章就介紹到這了,更多相關(guān)vue Router(v3.x) 路由傳參內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論