Nuxt JS with Laravel API - Building SSR Vue JS Apps 笔记3 Nuxt Pages
layouts/default中的nuxt标签作为nuxt的插槽,pages/index.vue会渲染至此。
新建pages/users.vue
route自动处理好了【必须有执行npm run dev】,打开 http://localhost:3000/users 即可看到页面结果。
view page source
因为:.nuxt/router.js中已经自动生成好了》》》
Creating Nested Pages
删除刚刚创建的users.vue
新建users文件夹及users/index.vue文件【必须有index.vue文件】
新建users/_id.vue文件
打开 http://localhost:3000/users/1 结果如上图,页面暂时用hard code的 X。后面再来写显示id之类的逻辑。
如果需要更深层级的:
继续加下一层的:新建users/_id文件夹,新建users/_id/index.vue文件:
打开:http://localhost:3000/users/1/ 结果如上图。
然后删除外部的_id.vue【然后新建users/_id/_id.vue】或者将外部的_id.vue移动到users/_id文件夹内,
打开:http://localhost:3000/users/1/2 结果如下:
如果需要更深层级的,继续重复上面操作即可。
可以看到.nuxt/router.js更新了:
Route Parameters
_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
输入:任意值,结果:
Nuxt Validate Method:
可以在pages文件夹【dynamic route】中,不能在components文件夹中。
修改_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>
输入数字结果:
输入字母结果:
如果注释掉validate方法:
打开:https://github.com/dzkjz/nuxt-learning-lesson
选择
即是本节代码。