vue頁(yè)面跳轉(zhuǎn)到新頁(yè)面之后,再由新頁(yè)面返回到原頁(yè)面時(shí)候若想返回調(diào)出原頁(yè)面的初始位置,怎么來(lái)解決這個(gè)問題呢?首先我們應(yīng)該在跳出頁(yè)面時(shí)候記錄下跳出的scrollY,返回原頁(yè)面的時(shí)候在設(shè)置返回位置為記錄下的scrolly即可,scrolly我用的是vuex狀態(tài)管理器來(lá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í)把位置存起來(lái) 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è)參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com