Javascript Vuejs如何在从url或路由器链接输入时阻止路由参数类型更改
路由参数更改类型Javascript Vuejs如何在从url或路由器链接输入时阻止路由参数类型更改,javascript,vue.js,vuejs2,vue-props,Javascript,Vue.js,Vuejs2,Vue Props,路由参数更改类型 当我从url输入时输入字符串 从路由器链接传递时进行编号 export default { name: "PostDetails", props: { id: Number }, created() { console.log(this.id); } }; 路由器.js { path: '/post/:id', name: 'postdetails', component: () => import('./compon
- 当我从url输入时输入字符串
- 从路由器链接传递时进行编号
export default {
name: "PostDetails",
props: {
id: Number
},
created() {
console.log(this.id);
}
};
路由器.js
{
path: '/post/:id',
name: 'postdetails',
component: () => import('./components/PostDetails.vue'),
props: true,
}
当我使用“路由器链接”时,它将以“数字”类型传递道具
但当我像这样在Url上输入它时:
http://localhost:8080/post/1
参数属性变为字符串
如何阻止参数属性类型不断变化?关于您的问题,您可以创建一个计算属性,将收到的参数转换为您想要的类型。将其转换为字符串的简单实现:
computed: {
idStr: function() {
return this.id + '';
}
}
查看我留下的评论,了解引擎盖下发生了什么。如果您想将路由参数保持为某一类型,它是从url输入的或通过路由器链接发送的,您可以通过在路由器道具上添加条件来实现
{
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将始终是数字类型,即使是从url输入的
vuejs有一个类似的论坛
当您以编程方式导航时,参数会按原样传递给组件(您传递的是一个数字),并基于这些参数构造URL。当您通过URL访问视图时,它所做的是分析URL并分解参数,然后传递给组件。这就是他们改变类型的原因。
{
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
},
},