[30天 Vue学好学满 DAY24] Vue Router-3

router-link

to 函数

指定导向,包含以下方法

<!-- 直接指定路径 -->
<router-link to="/">首页</router-link>
<!-- 与v-bind绑定 -->
<router-link :to="'/'">首页</router-link>
<!-- 与v-bind绑定,并指定path -->
<router-link :to="{path: '/'}">首页</router-link>
<!-- 具名路由并带入参数, /shop/1 -->
<router-link :to="{name: 'shop', params: {id: 1}}">Shop</router-link>
<!-- 具名路由并带入query参数, /shop?id=1 -->
<router-link :to="{name: 'shop', query: {id: 1}}">Shop</router-link>

replace 函数

取代预设的push函数进行导页,不留下浏览纪录(无法使用上下页)

<router-link to="/" replace>首页</router-link>

push & replace 导页

用於触发後导页ex: function中

// 指定字串
this.$router.push('/home');
// 指定path
this.$router.replace({path: '/home'});
// 具名路由
this.$router.push({name: 'home'});
// params
this.$router.replace({name: 'home', params: {id: '1'}});
// query
this.$router.push({name: 'home', query: {id: '1'}});

go函数

// 下一页
this.$router.go(1);
// 前一页
this.$router.go(-1);

导航守卫(Navigation Guards)

顾名思义极为在触发路由时进行管理,其中分为全域路由元件

beforeEach 全域前置守卫

所有路由动作前,都会经过此,全域守卫独立定义於路由外

to: 即将进入的对象。
from: 离开的对象。
next: 依赖的callback function,必需存在。

  • next(true) -> 执行
  • next(false) -> 不执行
  • next('xxx') -> 转至其他路由
  • next(error) -> 终止,并传至router.onError()

实作於route.js

// 若未登入,且不前往登入 -> 导向登入页
router.beforeEach((to, from, next) => {
    if (to.name !== 'Login' && !isAuth) next({ name: 'Login' })
    else next()
  })

beforeResolve 全域解析守卫

用法与beforeEach大致相同,差异於元件守卫、非同步路由原件解析完,才进行调用。

afterEach 全域後置钩子

跳转完触发,无next参数,不影响跳转,但可透过failure参数验证路由跳转是否成功。

beforeEnter 路由守卫

与上述的差异在於此为路由独享,并定义於路由中

routes: [
    {
        name: 'shop',
        path: "/shop/:id", // 带入参数 id
        component: () => import('../views/Shop.vue'),
        beforeEnter: (to, from, next) => {
            // ...
        }
    },
]

元件守卫

定义於元件中,类似於组件生命周期。

beforeRouteEnter
进入元件期前,提供to、from、next,但因为元件未建立,无法访问this
唯一支持next传递回调。

// 元件未建立,无法访问this
beforeRouteEnter(to, from, next) {
    if (to === 'xxx') next()
    else if (from === 'xxx')  next()
    else  next(false)
},

beforeRouteUpdate
路由改变前,此处改变为复用的改变,例如同元件但所带参数改变(/shop/1 -> /shop/2)

// 可访问this
  beforeRouteEnter(to, from, next) {
    // ...
},

beforeRouteLeave
离开元件时调用,常用於禁止提示是否离开(表单填写未完全)。

// this.done: 是否填写完成
beforeRouteLeave(to, from, next) {
    if (this.done) next(false) // 不进行换页
    else next()
},

router终於结束了
/images/emoticon/emoticon11.gif/images/emoticon/emoticon11.gif/images/emoticon/emoticon11.gif


有错误请不吝指教!
参考资料
https://vuejs.org/v2/guide
https://book.vue.tw/CH4/4-1-vue-router-intro.html
感谢各路大神
/images/emoticon/emoticon31.gif


<<:  #09 No-code 之旅 — 怎麽在 Client-side 抓取资料?SWR 简介

>>:  Day9 针对 ICS 攻击的骇客集团(1)

第一只狗勾页面-猴犬

继上次我说要先第一个用狗勾页面我就只先设置了那页的按钮,记得当你要对按钮下指令如asp-contro...

【Day4】前端React +Antd 的环境(Docker化)建立 (中)

相关工具的上手 1. javascript理解: 建议先入门 ( JavaScript 教程 ):J...

[DAY 08] TextItem

再来就可以进入另一个题型大宗---填充题 填充题可以对应到表单中的「简答」 如果回答方式中不包含特殊...

前端工程日记 30日 名片设计

如图 pancode: div 设计成 各种形状 三角形。五角形 六角形 的方法 制作参考引用 ht...

[Day18] NLP会用到的模型(二)-GRU

一. LSTM的问题 LSTM虽然非常强大,但LSTM也是有一个问题,就是计算时间较久导致执行速度较...