[Vue + TS] Using Route events inside Vue
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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> <h3>HelloTs</h3> <router-link to="/">Hello</router-link> </div> </template> <script lang="ts"> import Vue from ‘vue‘ import Component from ‘vue-class-component‘ @Component({}) export default class HelloTs extends Vue { created() { console.log("HelloTs created!") } beforeRouteEnter(to, from, next) { console.log("HelloTs: beforeRouteEnter") next() } beforeRouteLeave(to, from, next) { console.log("HelloTs: beforeRouteLeave") next() } } </script>
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 } })
以上是关于[Vue + TS] Using Route events inside Vue的主要内容,如果未能解决你的问题,请参考以下文章
[Vue] Lazy Load a Route by using the Dynamic Import in Vue.js
[Vue + TS] Use Properties in Vue Components Using @Prop Decorator with TypeScript
[Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript
[Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript(代码片