vue保存页面状态
在有些网页场景中,当跳转到新的页面时,需要缓存当前页面,以便用户返回时能够继续阅读上次浏览到的内容,提升用户体验,而不是重载页面。
在vue中,需要使用到<keep-alive></keep-alive>来缓存当前页面。
1、设置页面路由,打开store/index.js,添加以下代码:
const routes = [ { path: '/', name: 'Home', component: () => import('../views/Home.vue'), // 在路由中添加meta字段 meta:{ // 添加keepAlive字段,值true则缓存当前页面,false则不缓存 keepAlive: true } }, { path: '/index', name: 'index', component: () => import('../views/Index.vue'), meta:{
// 该页面不缓存 keepAlive:false } }, ]
2、在App.vue中使用<keep-alive></keep-alive>包裹路由:
<template>
<div id="app">
// keep-alive包裹需要缓存的页面
<keep-alive>
// 判断出keepAlive为true,缓存该页面
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
// 判断出keepAlive为false, 不缓存
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
3、在页面中进行页面跳转操作,当返回这个页面时,页面不会刷新,在input中输入的内容也不会改变
// src/views/Home.vue // 模板代码 <input v-model="content"> <button @click="go_index()"></button> // 脚本代码 export default{ name:"Home", data(){ return{ content:"" } }, methods:{ // 点击跳转 go_index(){ this.$router.push({name: "index"}); } }, // 监测路由变化 watch:{ $route(to, from){ console.log("......"); } } }
该方法是比较简单的一种缓存当前页面的方法。
浙公网安备 33010602011771号