在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Vue-router切換不同參數(shù)的共用路由問題?

Vue-router切換不同參數(shù)的共用路由問題?

圖片描述

parent.vue

//html
<button @click='alter(1)'>btn1</button>
<button @click='alter(2)'>btn2</button>
<router-view></router-view>

//js
alter(item) {
    this.$router.push({name:'classifyEdit',params:{id:item}});
}

child.vue

beforeRouteUpdate(to,from,next){
    console.log(to.params.id);
    next();
}

為什么只能顯示一個按鈕的id呢?如何才能點擊不同的按鈕顯示相應(yīng)的id

已經(jīng)解決,現(xiàn)在貼一下代碼
獲取不到參數(shù)的原因就是第一次路由渲染之后已經(jīng)存到了緩存里,第二次就不會觸發(fā)組件的生命周期鉤子,因此獲取不到第二個參數(shù),解決方法主要有監(jiān)聽路由參數(shù),使用路由導(dǎo)航守衛(wèi)beforeRouteUpdate,我用的后者,以下是代碼:

parent.vue

<button @click='alter(1)'>btn1</button>
<button @click='alter(2)'>btn2</button>
<Modal
    v-model="moralFlag"
    :title="moralTitle">
    <router-view></router-view>
    <div slot="footer"></div>
</Modal>

alter(item) {
    this.$router.push({name:'classifyEdit',query:{id:item.row.id}});
}

child.vue

beforeRouteUpdate(to,from,next){
    this.getData(to.query.id);
    next();
},
created(){
    this.getData(this.$route.query.id);
},
 methods: {
    getData(id){
        console.log(id)
}

兩個鉤子搭配使用
PS:制作過程中發(fā)現(xiàn)beforeRouteUpdate只能監(jiān)聽query參數(shù)無法監(jiān)聽params.

回答
編輯回答
憶當(dāng)年

你是在哪里console.log(this.$route.params.id)的. 點擊兩個按鈕, 點第一次的時候, router-view 剛創(chuàng)建, created可以調(diào)用, 獲取到id, 點第二次的時候, 就應(yīng)該是beforeRouteUpdate的鉤子函數(shù)了.
你再加一個

        beforeRouteUpdate(to, from, next){
            console.log(to.params.id);
            next();
        }

<router-view></router-iview> 多了一個 i, 請注意

2018年3月1日 22:50
編輯回答
笨小蛋

對于你這個問題我是這樣理解的
首先 我們點擊btn1按鈕,那么顯然會調(diào)用路由進入了classifyEdit 組件。所以傳入了id參數(shù)

但是如果我們這個時候再次點擊btn2的時候,其實我們已經(jīng)在name為classifyEdit的頁面了,router其實并沒有再次傳遞參數(shù),或者跳轉(zhuǎn) 因為name是相同的。所以你不管怎么點擊btn2 其實都是無效的。
是我淺薄了,對vue-router的理解不夠深入,重新翻看了 vue-router文檔
這里有介紹
介意樓主 看下vue-router

clipboard.png

2018年3月2日 01:00
編輯回答
愚念

建議改一下路由配置,不要把id做為參數(shù)傳入,比如:

{
    path: '/classifyEdit/:id',
    name: 'classifyEdit',
    component: classifyEdit,
    props: true
}

點擊的時候:

alert (id) {
    this.$router.push(`/classifyEdit/${id}`)
}

在子組件:

props: ['id'],
watch: {
  id (v) {
    console.log(v)
  }
}

這樣應(yīng)該就能每次取得值了

2018年8月11日 07:30