Navigation Guard: beforeRouteUpdate

notes

1. Demo

2. Key points

When the destination is the same as the current route, only the parameters have changed (such as from /users/1 ->  /users/2), you need to use  beforeRouteUpdate  to respond to this change 

beforeRouteUpdate(to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    next()
  },

3. Learning examples

Description: The route is the same but carries different parameters. There are two ways to deal with this: use beforeRouteUpdate or use watch to monitor the route

<template>
	<div>
		<ul>
			<li v-for="item in mes" :key="item.id" @click="toDetail(item.id, item.str)">
				{
   
   { item.str }}
				<!-- <router-link :to="`/home/message/detail?id=${item.id}&title=${item.str}`">{
   
   { item.str }}</router-link> -->
			</li>
		</ul>
		<hr />
		<router-view></router-view>
	</div>
</template>

<script>
import router from '../router/router'
export default {
	name: 'Message',
	data() {
		return {
			mes: [
				{ id: 0, str: '消息001' },
				{ id: 1, str: '消息002' },
				{ id: 2, str: '消息003' },
			],
		}
	},
    //方法一
	beforeRouteUpdate(to, from, next) {
		console.log('到', to, '从', from)
		// 判断路由是否不相等,不相等时继续执行
		if (to.fullPath != from.fullPath) {
			next()
		}
	},
	methods: {
		toDetail(id, str) {
			// console.log('@@',this.$route)
			router.push({ name: 'detail', query: { id, str } })
		},
	},
    //方法二
	// watch: {
	// 	$route(to, from) {
	// 		// console.log(to)
	// 		// console.log(from)
	// 		console.log('变化')
	// 	},
	// }
}
</script>

4. Mistake: Duplicate Routing 

There is a problem here when testing, and an error will be reported when entering the same route repeatedly

         

Solution: Modify the push method in main.js or use push() for exception capture

1.main.js

const VueRouterPush = vueRouter.prototype.push
vueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

2.catch(err=>{}) 

methods: {
		toUrl(id, str) {
			// console.log('@@',this.$route)
            //使用catch(err=>{}) 捕获异常
			router.push({ name: 'detail', query: { id, str } }).catch(err=>{
				console.log('错误',err)
			})
		},
	},

Guess you like

Origin blog.csdn.net/qq_47229902/article/details/128467008