场景:使用vue+vant做移动端开发,当打开a页面浏览到某个位置,点击跳转到b页面,然后再后退回a页面浏览的那个位置。
解决办法:使用store存储滚动条的位置。
store存储setScrollY的高度,代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{//设置属性 用来存储数据
setScrollY: 0,//页面滚动条显示高度
},
getters:{//对应方法 用来获取属性的状态
getScrollY:state => state.setScrollY,
},
mutations:{//更改属性的状态
setScrollYCommit(state, data){
state.setScrollY = data
}
},
actions:{//应用 mutation
setScrollYAction({commit}, data){
commit('setScrollYCommit',data)
}
},
})
export default store
在vue页面下,通过refs获取到dom节点,再获取scrollTop则是滚动条高度,例如:ref是scrollRef,则获取的是this.$refs.scrollRef.scrollTop(注意:ref一定是在overflow: auto的标签上)。代码如下:
...此处很多内容省略...
到此就能实现后退回原来浏览的位置了。