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

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

批注 2020-05-12 002101

新建pages/users.vue

批注 2020-05-12 002403

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

view page source

批注 2020-05-12 002511

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

批注 2020-05-12 002717

Creating Nested Pages

删除刚刚创建的users.vue

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

批注 2020-05-12 005339

新建users/_id.vue文件

批注 2020-05-12 005551

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

如果需要更深层级的:

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

批注 2020-05-12 010003

打开: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

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

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

批注 2020-05-12 010439


Route Parameters

批注 2020-05-12 014334

_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

输入:任意值,结果:

批注 2020-05-12 014950

Nuxt Validate Method:

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

批注 2020-05-12 015323

修改_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

输入数字结果:

批注 2020-05-12 015701

输入字母结果:

批注 2020-05-12 015743

如果注释掉validate方法:

批注 2020-05-12 015828

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

选择

批注 2020-05-12 020352

即是本节代码。

posted @ 2020-05-12 00:29  dzkjz  阅读(72)  评论(0)    收藏  举报