gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:55:18 25 4
gpt4 key购买 nike

我有如下路径

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

所以这是这样的

http://localhost:3000/board/112233333333

在上述情况下

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

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

33333333 id 的动态值。

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

最佳答案

As per the details in your question,


  • 您的网址是 http://localhost:3000/board/112233333333
  • 路由中的最后一个参数必须总共有 12 位(任意随机 12 位)

  • 112233333333 - 12 位

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



    we will work with this structure to get to your final result

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

    1. validate()方法必须返回 true 或 false
    export default {
    validate ({ params }) {
    return /^([0-9]{12,12})$/.test(params.id)
    }
    }

    2. params.idvalidate()方法将保存 id(url 参数中的值),在您的情况下它是 112233333333
    3. /^([0-9]{12,12})$/.test(params.id)将返回 true如果 id(url 参数中的值)有 12 位,否则返回 false true - 路线将被成功加载
    false - 将显示错误页面(未找到 404 页面 - 因为无法识别路线)

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

    1.在 created()生命周期钩子(Hook),使用 this.$route.params.id 从 url 中提取值

    2.拆分值 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

    关于nuxt.js - NUXT - 具有动态路径的路由 - 多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866867/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com