路由器的replace属性和编程式路由导航

313 阅读2分钟

「这是我参与2022首次更文挑战的第21天,活动详情查看:2022首次更文挑战」。


在本篇中我会和大家讲解一下路由对我们浏览器历史记录的影响和编程式路由导航,先说说这个浏览器的历史记录正常来说我们在每次点击跳转都会进入新的记录里面就比如:

image.png

在每一次点击浏览器都对我们的跳转进行记录像图中就像是栈的结构,浏览器记录就像是用push的方式进行添加。所以呢路由中就有一个属性就取消这种浏览器的默认行为就是通过replace属性来替换当前记录。

image.png 进行一下关于这个的总结:

<router-link>的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:<router-link replace .......>News</router-link>
<router-link :replace="true" to="/home/News">News</router-link>
简写:
<router-link replace to="/home/News">News</router-link>

接下来我就和大家讲讲全新的路由跳转方式就是编程式路由导航的相关内容了,在之前写的都是通过router-link标签进行的跳转,在这里呢我会放弃所以这个标签,下面就由我来说到说到:

<template>
	<div>
		<ul>
			<li v-for="m in messageList" :key="m.id">
				<!-- 跳转路由并携带params参数,to的字符串写法 -->
				<!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->

				<!-- 跳转路由并携带params参数,to的对象写法 -->
				<router-link :to="{
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				}">
					{{m.title}}
				</router-link>
				<button @click="pushShow(m)">push查看</button>
				<button @click="replaceShow(m)">replace查看</button>
			</li>
		</ul>
		<hr>
		<router-view></router-view>
	</div>
</template>

<script>
	export default {
		name:'Message',
		data() {
			return {
				messageList:[
					{id:'001',title:'消息001'},
					{id:'002',title:'消息002'},
					{id:'003',title:'消息003'}
				]
			}
		},
		methods: {
			pushShow(m){
				this.$router.push({
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				})
			},
			replaceShow(m){
				this.$router.replace({
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				})
			}
		},
	}
</script> 

编程式路由导航

  1. 作用:不借助<router-link> 实现路由跳转,让路由跳转更加灵活

  2. 具体编码:

    //$router的两个API 
    this.$router.push({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    
    this.$router.replace({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    this.$router.forward() //前进
    this.$router.back() //后退
    this.$router.go() //可前进也可后退
    

    在这里给大家讲一个小功能,这个功能呢就是控制浏览器历史记录的模式的