Vue Router_3、replace、编程式导航、缓存路由组件

1.replace属性

<router-link>的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式

  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push

  3. 如何开启replace模式:<router-link replace .......>News</router-link>

总结:浏览记录本质是一个栈,默认push,点开新页面就会在栈顶追加一个地址,后退,栈顶指针向下移动,改为replace就是不追加,而将栈顶地址替换。


2.编程式路由导航

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

具体编码:

//$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() //可前进也可后退

src\pages\Message.vue

<template>
    <div>
        <ul>
        <li v-for="m in messageList" :key="m.id">
            <!-- 跳转路由并携带params参数,to的对象写法 -->
            <router-link 
            :to="{
                name:'xiangqing',//params写法必须写成name,不能用path
                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){
            //console.log(this.$router);
            this.$router.push({
                name:'xiangqing',//params写法必须写成name,不能用path
                query:{
                    id:m.id,
                    title:m.title
                }
            });
        },
        replaceShow(m){
             this.$router.replace({
                name:'xiangqing',//params写法必须写成name,不能用path
                query:{
                    id:m.id,
                    title:m.title
                }
            });
        }
    },
    

}
</script>

3.缓存路由组件

作用:让不展示的路由组件保持挂载,不被销毁。

具体编码:

<keep-alive include="News"> 
    <router-view></router-view>
</keep-alive>

缓存多个
<keep-alive :include="['News','News']">

缓存全部
<keep-alive>

注意:该组件在哪个组件的 <router-view>标签里呈现就在对应组件的 <router-view>标签外包一层<keep-alive>标签,不指定include会把里面的所有组件都缓存。

image


posted @ 2022-04-14 18:19  青仙  阅读(691)  评论(0编辑  收藏  举报