Nuxt JS with Laravel API - Building SSR Vue JS Apps 笔记3 Nuxt Pages

layouts/default中的nuxt标签作为nuxt的插槽,pages/index.vue会渲染至此。

-2020-05-12-002101_thumb2

新建pages/users.vue

-2020-05-12-002403_thumb2

route自动处理好了【必须有执行npm run dev】,打开 http://localhost:3000/users 即可看到页面结果。

view page source

-2020-05-12-002511_thumb1

因为:.nuxt/router.js中已经自动生成好了》》》

-2020-05-12-002717_thumb1

Creating Nested Pages

删除刚刚创建的users.vue

新建users文件夹及users/index.vue文件【必须有index.vue文件】

-2020-05-12-005339_thumb1

新建users/_id.vue文件

-2020-05-12-005551_thumb1

打开 http://localhost:3000/users/1 结果如上图,页面暂时用hard code的 X。后面再来写显示id之类的逻辑。

如果需要更深层级的:

继续加下一层的:新建users/_id文件夹,新建users/_id/index.vue文件:

-2020-05-12-010003_thumb2

打开:http://localhost:3000/users/1/ 结果如上图。

然后删除外部的_id.vue【然后新建users/_id/_id.vue】或者将外部的_id.vue移动到users/_id文件夹内,

打开:http://localhost:3000/users/1/2 结果如下:

-2020-05-12-010256_thumb1

如果需要更深层级的,继续重复上面操作即可。

可以看到.nuxt/router.js更新了:

-2020-05-12-010439_thumb4


Route Parameters

-2020-05-12-014334_thumb1

_id/_id.vue:

<template>
  <div>
    <h2>This is user's id: {{$route.params.id}} second nested page</h2>
  </div>
</template>

<script>
  export default {
    name: "_id.vue"
  }
</script>

<style scoped>

</style>

接下来,修改_id/index.vue:

<template>
  <div>
    <h2>This is first nested page</h2>
    <input type="text" v-model="id">
    <button @click="loadUser">Load user</button>
  </div>
</template>

<script>
  export default {
    name: "index.vue",
    data() {
      return {
        id: '',
      }
    },
    methods: {
      loadUser() {
        this.$router.push(`/users/1/${this.id}`);
      },
    }
  }
</script>

<style scoped>

</style>

打开页面:http://localhost:3000/users/11 

-2020-05-12-014903_thumb1

输入:任意值,结果:

-2020-05-12-014950_thumb1

Nuxt Validate Method:

可以在pages文件夹【dynamic route】中,不能在components文件夹中。

-2020-05-12-015323_thumb1

修改_id/_id.vue文件如下【就是使用正则判断params是否为数字】

<template>
  <div>
    <h2>This is user's id: {{$route.params.id}} second nested page</h2>
  </div>
</template>

<script>
  export default {
    name: "_id.vue",
    validate(context) {
      return /^\d+$/.test(context.params.id);
    },
  }
</script>

<style scoped>

</style>

-2020-05-12-015642_thumb1

输入数字结果:

-2020-05-12-015701_thumb1

输入字母结果:

-2020-05-12-015743_thumb1

如果注释掉validate方法:

-2020-05-12-015828_thumb1

打开:https://github.com/dzkjz/nuxt-learning-lesson

选择

-2020-05-12-020352_thumb1

即是本节代码。

posted @ 2020-05-12 14:36  dzkjz  阅读(41)  评论(0)    收藏  举报