简体   繁体   English

Vuejs如何从URL或router-link输入时停止更改路由参数类型

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

Route params changes Type 路线参数更改类型

  • to String when I input from url URL输入时,将其转换为String

  • to Number when passed from router-link . router-link传递到Number时。

router.js router.js

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

when I use the "router-link" it will pass the prop as type "number" 当我使用“ 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>

if I click the element inside router-link it will redirect to another page and the "params.id" is type Number . 如果单击 router-link内的元素,它将重定向到另一页,并且“ params.id”的类型为Number

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

But when I input it on Url like this: 但是当我像这样在Url上输入它时:

http://localhost:8080/post/1

the params prop becomes String params道具变成String

how can I stop the params prop Type from constantly changing? 如何阻止params prop类型不断变化?

If you want to maintain the route params to a certain Type weather it was entered from a url or sent via router-link you can do it by adding a condition on the router props. 如果要将路线参数保持为某个特定类型的天气,可以从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
  },
},

now the Id in the props will always be a Number Type, even if entered from url. 现在,即使从网址输入,道具中的ID仍将始终是数字类型。

there is a forum from vuejs similar to this 来自vuejs的一个论坛与此类似

Router-vue, props type number didn't cast Router-Vue,道具类型编号未投放

Regarding your question, you can create a computed property, which transforms the received parameter to the type you wish. 关于您的问题,您可以创建一个计算属性,该属性将接收到的参数转换为所需的类型。 Trivial implementation to convert it to string: 简单的实现将其转换为字符串:

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

Check the comment I left to understand what is happening under the hood. 查看我留下的评论,以了解幕后情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM