簡體   English   中英

Vuejs如何從URL或router-link輸入時停止更改路由參數類型

[英]Vuejs How to stop route params Type from changing when entered from url or router-link

路線參數更改類型

  • URL輸入時,將其轉換為String

  • router-link傳遞到Number時。

router.js

{
  path: '/post/:id',
  name: 'postdetails',
  component: () => import('./components/PostDetails.vue'),
  props: true,
}

當我使用“ router-link”時,它將作為“ number”類型傳遞道具

  <router-link :to="{name:'postdetails', params:{id: post.id}}">
      <div class="title" @click="viewPost">
        <h4>{{post.user_username}} -</h4>
        <p>{{post.title}}</p>
      </div>
    </router-link>

如果單擊 router-link內的元素,它將重定向到另一頁,並且“ params.id”的類型為Number

export default {
  name: "PostDetails",
  props: {
    id: Number
  },
  created() {
    console.log(this.id);
  }
};

但是當我像這樣在Url上輸入它時:

http://localhost:8080/post/1

params道具變成String

如何阻止params prop類型不斷變化?

如果要將路線參數保持為某個特定類型的天氣,可以從URL輸入該參數,或者通過router-link發送該參數,則可以通過在路由器道具上添加條件來實現。

{
  path: '/post/:id',
  name: 'postdetails',
  component: () => import('./components/PostDetails.vue'),
  props(route) { // we keep the params.id Type from changing when entered from url
    let props = { ...route.params }
    props.id = parseInt(props.id)
    return props
  },
},

現在,即使從網址輸入,道具中的ID仍將始終是數字類型。

來自vuejs的一個論壇與此類似

Router-Vue,道具類型編號未投放

關於您的問題,您可以創建一個計算屬性,該屬性將接收到的參數轉換為所需的類型。 簡單的實現將其轉換為字符串:

computed: {
    idStr: function() {
        return this.id + '';
    }
}

查看我留下的評論,以了解幕后情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM