[Vue + TS] Using Route events inside Vue

vue-router introduces new hooks into the component. In this lesson we’ll show you how to use these new hooks in your class based Vue components in TypeScript. We’ll also go over how we can create and use routes in Vue.

Default component:

复制代码
<template>
  <div class="hello">
    <h1>{{ message }}</h1>
    <button @click="clicked">Click</button>
    <router-link to="/hello-ts">Hello Ts</router-link>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'

@Component({})
export default class Hello extends Vue {
  message: string = 'Welcome to Your Vue.js App'

  get fullMessage() {
    return `${this.message} from Typescript`
  }

  created() {
    console.log('created');
  }

  beforeRouteEnter(to, from, next) {
    console.log("Hello: beforeRouteEnter")
    next()
  }

  beforeRouteLeave(to, from, next) {
    console.log("Hello: beforeRouteLeave")
    next()
  }

  clicked() {
    console.log('clicked');
  }
}
复制代码

 

Create a second component:

复制代码
<template>
    <div>
        <h1>Hello Ts</h1>
        <router-link to='/'>Hello Vue</router-link>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import Route from 'vue-router';

@Component({})
export default class HelloTs extends Vue{
    created() {
        console.log("Hello TS created")
    }

    beforeRouteEnter(to: Route, from: Route, next: Function) {
        console.log("beforeRouteEnter")
        next();
    }

    beforeRouteLeave(to: Route, from: Route, next: Function) {
        console.log("beforeRouteLeave")
         next();
    }
}
</script>
复制代码

Checkout Doc

 

There are tow route events, "beforeRouteEnter" and "beforeRouteLeave", each lifecycle hooks accepts three params "to, from , next", just like middlewares in nodejs, we need to call "next()" to make everything works.

 

Also we need to register the route link before using Vue.

hooks.ts:

import Component from 'vue-class-component'

Component.registerHooks([
    'beforeRouteEnter',
    'beforeRouteLeave'
])

 

main.ts:

复制代码
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import './hooks'

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})
复制代码

 

posted @   Zhentiw  阅读(1341)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-09-11 [Javascript] Other functor
点击右上角即可分享
微信分享提示