vue 移动端项目切换页面,页面置顶

时间:2023-03-09 05:22:33
vue 移动端项目切换页面,页面置顶

之前项目是pc端是使用router的方式实现置顶的

//main.js

router.afterEach((to, from, next) => {
window.scrollTo(0, 0)
})

但是改了移动端就没有效果了,稍微查了一下,好像说是要body里才有用。

可能与我使用了vux-ui有关

在深究router方式还是找新方法的选择上,我选了后者,

//自定义的common.js

// 这个方法通过递归找到滚动的元素,用于置顶页面
function getScrollParent (node) {
if (node == null) {
return null
}
if (node.scrollHeight > node.clientHeight) {
return node
} else {
return getScrollParent(node.parentNode)
}
}

export {getScrollParent}
 

// 页面文件,例如hello.vue

// 引入
import {isEmptyObj, getScrollParent} from '@/common/utils/common' //在mounted钩子函数调用
mounted () {
const element = getScrollParent(this.$el)
element.scrollTop = 0
this.initCanvas()
},

用以上方法,解决问题