Javascript 可以设置特定的VueRouter道具吗?
使用VueRouter,我希望能够进入以下URL:Javascript 可以设置特定的VueRouter道具吗?,javascript,vue.js,ecmascript-6,vuejs2,vue-router,Javascript,Vue.js,Ecmascript 6,Vuejs2,Vue Router,使用VueRouter,我希望能够进入以下URL: category/apple category/banana category/pear 是否可以将路由器参数限制为特定字符串?(香蕉、苹果、梨) 我在文档中找不到任何与此相关的内容。我在谷歌上找到了一些不起作用的其他解决方案: { path: 'category/:categoryType', props: true, /*props: { validator: functi
category/apple
category/banana
category/pear
{
path: 'category/:categoryType',
props: true,
/*props: {
validator: function (value) {
return ( value === 'banana' || value === 'apple' || value === 'pear');
}
},*/
component: someComponent
},
我现在能想到的唯一解决方案是在组件中的
created()
中验证这一点 我认为此代码是您案例的解决方案:
const allowedCategoryNames = ['apple', 'banana', 'pear'];
const categoryRoutePath = '/category/:categoryName(' + allowedCategoryNames.join('|') + ')';
{
path: categoryRoutePath,
props: true,
component: someComponent
},
在您的组件中,您可以获得如下当前cutegory名称:
const currentCategory = this.$route.params.categoryName;
这应该有效()
此处可以找到一些示例:如果您设置
props:true
,则可以使用this.categoryName
访问路由参数。我是否可以将整个categoryRoutePath
变量作为字符串添加到路径下:
?为什么必须在变量中设置它?(没有测试过这个是的,afk)。@wellhellothere,我已经测试了上面的代码=)当然,你可以添加一个字符串文字而不是变量,但是如果你扩展了类别名称列表,你需要编辑路由路径。无论如何,您可以将path:categoryRoutePath
替换为path:'/category/:categoryName(苹果|香蕉|梨)
。