您好,登錄后才能下訂單哦!
vue頁(yè)面跳轉(zhuǎn)到新頁(yè)面之后,再由新頁(yè)面返回到原頁(yè)面時(shí)候若想返回調(diào)出原頁(yè)面的初始位置,怎么來解決這個(gè)問題呢?首先我們應(yīng)該在跳出頁(yè)面時(shí)候記錄下跳出的scrollY,返回原頁(yè)面的時(shí)候在設(shè)置返回位置為記錄下的scrolly即可,scrolly我用的是vuex狀態(tài)管理器來保存的。整個(gè)環(huán)境是基于vue-cli搭建的
一、main.js里面配置vuex
//引用vuex import Vuex from 'vuex' Vue.use(Vuex)
二、main.js里面vuex狀態(tài)管理
var store = new Vuex.Store({ state: { recruitScrollY:0 }, getters: { recruitScrollY:state => state.recruitScrollY }, mutations: { changeRecruitScrollY(state,recruitScrollY) { state.recruitScrollY = recruitScrollY } }, actions: { }, modules: {} })
三、這里列舉一個(gè)listview頁(yè)面和詳情頁(yè)面,listview頁(yè)面就是原始頁(yè)面,listview頁(yè)面跳轉(zhuǎn)到詳情頁(yè)面,然后返回時(shí)候回到跳轉(zhuǎn)到詳情頁(yè)面之前的位置,在listview頁(yè)面編寫代碼
beforeRouteLeave(to, from, next) { let position = window.scrollY //記錄離開頁(yè)面的位置 if (position == null) position = 0 this.$store.commit('changeRecruitScrollY', position) //離開路由時(shí)把位置存起來 next() }, watch: { '$route' (to, from) { if (to.name === 'NewRecruit') {//跳轉(zhuǎn)的的頁(yè)面的名稱是"NewRecruit",這里就相當(dāng)于我們listview頁(yè)面,或者原始頁(yè)面 let recruitScrollY = this.$store.state.recruitScrollY window.scroll(0, recruitScrollY) } } }
四、若要避免created生命周期的執(zhí)行,可以使用緩存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
以上這篇vue頁(yè)面跳轉(zhuǎn)后返回原頁(yè)面初始位置方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。