日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue 记录滚动位置_vue 路由跳转记住滚动位置,返回时回到上次滚动位置

發(fā)布時(shí)間:2025/4/16 vue 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue 记录滚动位置_vue 路由跳转记住滚动位置,返回时回到上次滚动位置 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

方法一: 利用Keep-Alive和監(jiān)聽器

1.首先在路由中引入需要的模塊

{

path: ‘/scrollDemo’,

name: ‘scrollDemo’,

meta: {

keepAlive:true //需要緩存

},

component: resolve=> { require([‘../view/scrollDemo.vue’],

resolve) }

}

2.在App.vue中設(shè)置緩存組件

//緩存組件跳轉(zhuǎn)的頁面

//非緩存組件跳轉(zhuǎn)頁面

3.在頁面注冊(cè)對(duì)應(yīng)的事件

(1). 在data中定義一個(gè)初始值 scroll

(2). 在mouted中 ,mouted中的方法代表dom已經(jīng)加載完畢

window.addEventListener('scroll', this.handleScroll);

(3).methods 用于存放頁面函數(shù)

handleScroll () {this.scroll = document.documentElement &&document.documentElement.scrollTop

console.log(this.scroll)

}

4.activated 為keep-alive加載時(shí)調(diào)用

activated() {if(this.scroll > 0){

window.scrollTo(0, this.scroll);this.scroll = 0;

window.addEventListener('scroll', this.handleScroll);

}

}

5.deactivated 頁面退出時(shí)關(guān)閉事件 防止其他頁面出現(xiàn)問題

deactivated(){

window.removeEventListener('scroll', this.handleScroll);

}

方法二:利用beforeRouteLeave和watch

main.js中:

var store = newVuex.Store({ //記得先引入vuex

state: {

recruitScrollY:0},

getters: {

recruitScrollY: state=>state.recruitScrollY

},

mutations: {

changeRecruitScrollY(state, recruitScrollY) {

state.recruitScrollY=recruitScrollY;

}

},

actions: {

},

modules: {}

})

組件中(/flashSaleListX為當(dāng)前組件,即需要記住滾動(dòng)條位置的組件):

methods:{

isTabRoute:function() {if (this.$route.path === '/flashSaleListX') {

let recruitScrollY= this.$store.state.recruitScrollY

document.documentElement.scrollTop=recruitScrollY;

}

}

},

watch: {'$route': 'isTabRoute',

},

beforeRouteLeave(to, from, next) {

let position= document.documentElement && document.documentElement.scrollTop; //記錄離開頁面時(shí)的位置

if (position == null) position = 0

this.$store.commit('changeRecruitScrollY', position) //離開路由時(shí)把位置存起來

next()

}

方法三:(適用于方法二獲取不到滾動(dòng)位置)

組件中:

··· 內(nèi)容···

beforeRouteEnter(to, from, next) {

next(vm=>{

const div1=vm.$refs.div1//記錄滾動(dòng)高度

div1.scrollTop =vm.scroll

})

},

beforeRouteLeave(to, from, next) {

const div1= this.$refs.div1;this.scroll =div1.scrollTop; //data中記得定義變量scroll

next()

}

注:在路由配置中,記住滾動(dòng)的頁面keep-alive需為true

總結(jié)

以上是生活随笔為你收集整理的vue 记录滚动位置_vue 路由跳转记住滚动位置,返回时回到上次滚动位置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。