vue.js:路由跳转后自动定位到页面顶部(vue@3.2.37)

发布时间 2023-07-27 14:34:17作者: 刘宏缔的架构森林

一,代码:

说明:在main.js中增加代码,在路由跳转后滑动到顶部,如下

//页面加载后滑至顶部

1
2
3
router.afterEach(() => {
    window.scrollTo(0,0);
});

main.js的例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { createApp } from 'vue'
import App from './App.vue'
import router from './route'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
//element-plus 的中文化
import locale from 'element-plus/lib/locale/lang/zh-cn'
//element-plus 的icon
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//引入css公共样式
import '../public/static/css/global.css'
//页面加载后滑至顶部
router.afterEach(() => {
    //NProgress.done();
    window.scrollTo(0,0);
});
 
//启动app
const app = createApp(App)
 
// 全局注册el-icon
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
app.use(router)
app.use(ElementPlus,{locale})
app.mount('#app')

二,查看效果:

原效果:

添加代码后效果:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/07/24/vue-js-lu-you-tiao-zhuan-hou-zi-dong-ding-wei-dao-ye-mian-ding-bu-vue-3-2-37/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,查看vue.js的版本

liuhongdi@lhdpc:/data/vue/touch$ npm list vue
touch@0.1.0 /data/vue/touch
├─┬ vue-router@4.0.16
│ └── vue@3.2.37 deduped
├─┬ vue@3.2.37
│ └─┬ @vue/server-renderer@3.2.37
│   └── vue@3.2.37 deduped
└─┬ vuedraggable@4.1.0
  └── vue@3.2.37 deduped