vue页面跳转后返回原页面初始位置方法

栏目: 编程语言 · JavaScript · 发布时间: 7年前

内容简介:下面小编就为大家分享一篇vue页面跳转后返回原页面初始位置方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

vue页面跳转到新页面之后,再由新页面返回到原页面时候若想返回调出原页面的初始位置,怎么来解决这个问题呢?首先我们应该在跳出页面时候记录下跳出的scrollY,返回原页面的时候在设置返回位置为记录下的scrolly即可,scrolly我用的是vuex状态管理器来保存的。整个环境是基于vue-cli搭建的

一、main.js里面配置vuex

//引用vuex 
import Vuex from 'vuex' 
Vue.use(Vuex) 

二、main.js里面vuex状态管理

var store = new Vuex.Store({ 
 state: { 
 recruitScrollY:0 
 }, 
 getters: { 
 recruitScrollY:state => state.recruitScrollY 
 }, 
 mutations: { 
 changeRecruitScrollY(state,recruitScrollY) { 
 state.recruitScrollY = recruitScrollY 
 } 
 }, 
 actions: { 
 
 }, 
 modules: {} 
}) 

这里列举一个listview页面和详情页面,listview页面就是原始页面,listview页面跳转到详情页面,然后返回时候回到跳转到详情页面之前的位置,在listview页面编写代码

beforeRouteLeave(to, from, next) { 
 let position = window.scrollY //记录离开页面的位置 
 if (position == null) position = 0 
 this.$store.commit('changeRecruitScrollY', position) //离开路由时把位置存起来 
 next() 
 }, 
 watch: { 
 '$route' (to, from) { 
 if (to.name === 'NewRecruit') {//跳转的的页面的名称是"NewRecruit",这里就相当于我们listview页面,或者原始页面 
 let recruitScrollY = this.$store.state.recruitScrollY 
 window.scroll(0, recruitScrollY) 
 } 
 } 
 } 

四、若要避免created生命周期的执行,可以使用缓存keepAlive,这里也分享一下

(1)App.vue template

<keep-alive v-if="$route.meta.keepAlive"> 
 <router-view></router-view> 
 </keep-alive> 
 <router-view v-if="!$route.meta.keepAlive"></router-view> 

(2)router index.js

Vue.use(Router) 
 
const routerApp = new Router({ 
 routes: [{ 
 { 
 path: '/NewRecruit', 
 name: 'NewRecruit', 
 component: NewRecruit, 
 meta: { 
 keepAlive: true 
 } 
 }, 
 { 
 path: '/NewRecruitDesc/:id', 
 name: 'NewRecruitDesc', 
 component: NewRecruitDesc, 
 meta: { 
 keepAlive: true 
 } 
 }, 
 { 
 path: '/SubmitSucess', 
 name: 'SubmitSucess', 
 component: SubmitSucess, 
 meta: { 
 keepAlive: false 
 } 
 } 
 ] 
}) 
 
export default routerApp 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Build Your Own Web Site the Right Way Using HTML & CSS

Build Your Own Web Site the Right Way Using HTML & CSS

Ian Lloyd / SitePoint / 2006-05-02 / USD 29.95

Build Your Own Website The Right Way Using HTML & CSS teaches web development from scratch, without assuming any previous knowledge of HTML, CSS or web development techniques. This book introduces you......一起来看看 《Build Your Own Web Site the Right Way Using HTML & CSS》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换