[鼠年全马] W26 - Vue心得笔记 - Vue Router分页好蚌蚌(下)

继上上週Vue Router基本篇之后
这週要来提到一些我个人在实务上常用到的功能


#动态Router

首先先谈谈动态Router
我们常常会需要在导页时 传入一些参数资讯
例如:
工具:
/tools/wrench
/tools/hammer
/tools/scissors

要进入的页面:
/page/1
/page/2
/page/3/5

导页时 我们就可以利用动态Router的方式去抓到参数

以工具来说, router设定上可以改成这样:
/tools/:tool

接着页面中就可以利用$route.params.tool来抓到传入的tool
完整範例:

const routes = [  {    path: '/tools/:tool',    name: 'Tools',    component: Tools  },  ...]
<div>身为一个工程师,有个 {{ $route.params.tool }} 在身边是很合逻辑的</div>

http://img2.58codes.com/2024/20118686OzE6n5wBeK.jpg

当然要多个参数也是没问题
/tools/:job/:tool/:number

<div>    身为一个 {{ $route.params.job }}    有 {{ $route.params.number }} 个 {{ $route.params.tool }} 在身边是很合逻辑的</div>

不过这种方式传参数会有个问题, 就是少填一个参数页面就会无法正常呈现, 这点需要注意
顺便讲一下, 如果要用原始的问号传参数的方式
例如 /tools?tool=hammer
页面上可以使用$route.query.tool来取得值

<div>雷神锁耳拿着他的大 {{ $route.query.tool }} </div>

这个参数就可填可不填

两种方式搭配使用也是可以的
/tools/:job/:tool?number=1


#巢状路由

第二个常用的就是 巢状路由
例如Google帐户设定页面
http://img2.58codes.com/2024/20118686VF8Lolc6j6.jpg
当在首页或是个人资讯, 这两个所呈现的元件一定不会是一样的
那到底在哪个页面需要用到什么元件
就可以用巢状路由来控制

而巢状路由写法, 只需要在原本的router设定内加一个children阵列, 阵列内放的物件跟原本的route一样, 像这样:

const routes = [  ...,  {    path: '/account/',    name: 'Account',    component: Account,    children: [      //这里放route物件      {        path: 'index', //记得前面不需要斜线        name: '首页',        component: AccountIndex,      },      {        path: 'userinfo', //记得前面不需要斜线        name: '个人资讯',        component: AccountUserInfo,      },      ...    ]  }]

接着Account元件上要记得加上*< router-view />*, 子页才会呈现喔~

<template>  <div>    <h1>This is an Account page</h1>    <router-view />  </div></template>

要做子页中的子页一样也是没问题的

const routes = [  ...,  {    path: '/account/',    name: 'Account',    component: Account,    children: [      {        path: 'index', //记得前面不需要斜线        name: '首页',        component: AccountIndex,        children: [          {            path: 'subpage1',             name: '子子页1',            component: AccountIndexSubpage1,                      },        ]      },      {        path: 'userinfo',         name: '个人资讯',        component: AccountUserInfo,      },      ...    ]  }]

#自订导页

这个我个人觉得超实用而且设定超简单的方法
使用情境是使用者常常会自作聪明在url上乱打, 但系统没有判断这个所以还是让他通过了, 然后就帮他导页到奇怪的地方, 这时候客诉电话就来了~~(凸)~~

为了防止这种情况发生
我们可以在routes设定最后面加上这段

{  path: '*',  redirect: '/',}

path: '*' 意思是 任何路由
redirect: '/' 意思是 导页到/
合起来就是 - 任何路由都导页到/

也就是说不管使用者乱打什么, 最后都会被导页到首页, 也就不会有客诉电话了http://img2.58codes.com/2024/emoticon34.gif

要注意的是, 这段一定要放在最后面
假如放在前面, 他就会先被判断到, 这样就算我们打上已经存在的路由也会被导页到首页去

完整routes程式码:

const routes = [  ...,  {    path: '/about',    name: 'About',    component: About,  },  ...,  {    path: '*',    redirect: '/',  },]

以上就是个人在实务上超常使用到的功能
vue-router到这结束~


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章