NUXT - 具有动态路径的路由 - 多个参数

NUXT - Route with dynamic path - multiple parameters

我有如下的路由路径

路径:'/board/:type(\d{2}):subtype(\d{2}):id(\d+)'

所以这是这样的

http://localhost:3000/board/112233333333

在上面的例子中

11type 的动态值(最多两位数)

22 子类型 的动态值(最多两位数)

33333333id.

的动态值

任何人都可以告诉我如何为这个创建文件夹结构吗?如果不可能,处理这种情况的最佳想法是什么?

As per the details in your question,

  1. 你的url是http://localhost:3000/board/112233333333

  2. 路由中的最后一个参数必须有总共12位数字(任意随机12位数字)

112233333333 - 12 位数字

We will work with below page structure to get to your final result

_id.vue中使用validate()检查此路由是否有效。

1.validate() 方法必须 return true 或 false

export default {
    validate ({ params }) {
        return /^([0-9]{12,12})$/.test(params.id)
    }    
}

2.params.id in validate() 方法将保存 id (value in url param) ,在你的情况下它是 112233333333

3./^([0-9]{12,12})$/.test(params.id) 将 return true 如果 id (url 参数中的值) 有 12 个数字,否则 return false

true - 路由将加载成功

false - 将显示错误页面 (找不到 404 页面 - 因为无法识别路线)

如果验证方法 return 为 true ,那么这意味着允许加载页面。现在我们必须利用 vuejs 生命周期钩子来进行下一步。

1.In created() 生命周期钩子,使用 this.$route.params.id

从 url 中提取值

2.Split 值 this.$route.params.id 使用正则表达式。使用 match 方法分组为您需要的格式。在您的情况下,您已将其拆分为 2、2、8 位数字。下面片段中的正则表达式正是这样做的

created(){

    var _id = this.$route.params.id;
    var regex = /^([0-9]{2,2})([0-9]{2,2})([0-9]{8,8})$/;
    var contents = _id.match(regex);

    this.type = contents[1];
    this.subtype = contents[2];
    this.id = contents[3]; 
}

经过正确验证后,现在您拥有了所需的所有值。您可以忽略 contents[0].

中的值

下面是用于测试我在此处描述的方法的代码。

将代码放入 _id.vue 文件并验证结果。

/* template code */
<template>
  <section>
    <h3>in board _id</h3>    
    <div>
        <div>type = {{type}}</div>
        <div>subtype = {{subtype}}</div>
        <div>id = {{id}}</div>
        <div>urlParam = {{$route.params}}</div>
    </div>
  </section>
</template>

/* script */
<script>
export default {
    /* variables */
    data(){
        return{
            type : null,
            subtype : null,
            id : null
        }
    },
    /* route validation */
    validate ({ params }) {
        return /^([0-9]{12,12})$/.test(params.id)
    },
    /* extracting url params */
    created(){
        var _id = this.$route.params.id;
        var regex = /^([0-9]{2,2})([0-9]{2,2})([0-9]{8,8})$/;
        var contents = _id.match(regex);
        this.type = contents[1];
        this.subtype = contents[2];
        this.id = contents[3]; 
    }
}
</script>

参考https://nuxtjs.org/api/pages-validate