<> Method for monitoring route change

<>1.watch
It should be noted that , Only changes in sub routes can be monitored .
* Person.vue <template> <div id="person"> <h1 @click="toMain"> Personal Center </h1> <p>
This is the personal center , Welcome to personal information </p> <router-link to="/person/user"> User information </router-link> <
router-view></router-view> </div> </template> <script> export default { name:
'Person', data () { return { } }, watch: { $route(to, from) {
// Here you can add the method to trigger when you listen to the route change console.log(to.path) console.log(from.path) } }, methods:
{ toMain() { this.$router.go(-1) } } } </script> <style> #person { color:
greenyellow; } #person p { background: pink; } </style>
-router.js
import Vue from 'vue' import Router from 'vue-router' import App from
'../App.vue' import Main from '../components/Main.vue' import Person from
'../components/Person.vue' import User from '../components/User.vue' Vue.use(
Router) export default new Router({ routes: [ { path: '/', name: 'App',
component: App, children: [{ path: 'main', name: 'Main', component: Main }] }, {
path: '/person/', name: 'Person', component: Person, children: [ { path: 'user'
, name: 'User', component: User } ] } ] })
<>2. Use routing hook function beforeRouteEnter beforeRouteUpdate beforeRouteLeave
Hook function beforeRouteEnter,beforeRouteLeave It can monitor the change of its own route
beforeRouteUpdate It monitors the changes of sub routes The disadvantage of hook function is that it does not send operation to obtain `this` beforeRouteEnter (to, from,
next) { // The corresponding route of the component is rendered confirm Pre invocation // no ! can ! Get component instance `this` // Because before the hook is executed , The component instance has not been created
console.log(to.path) console.log(from.path) if(to.path == '/person/user'){
console.log('ok!') } next() }, beforeRouteUpdate (to, from, next) { //
Change in current route , But called when the component is reused // for instance , For a path with dynamic parameters /foo/:id, stay /foo/1 and /foo/2 When jumping between ,
// Because it renders the same Foo assembly , Therefore, component instances are reused . And this hook will be called in this case . // Can access component instances `this` },
beforeRouteLeave (to, from, next) { // Called when the navigation leaves the corresponding route of the component // Can access component instances `this` },
<> Let's make progress together , What questions can I ask about the article , Try to answer . If you find any problems, please point them out , thank you .

Technology