vue-cli 跳转到页面指定位置

原文关注公众号,后台里留言可进行提问,可在后台留言向作者提问解答问题!

https://mp.weixin.qq.com/s?__biz=Mzg3NTAzMzAxNA==&mid=2247484254&idx=1&sn=361bbb2113be3eeda3802f0a805c5705&chksm=cec6fb87f9b1729174e3ae66bf9693207386256c964499c098fb8a6cc14b4ba266bc271073a3&token=689492939&lang=zh_CN#rd

方法1:在路由守卫中处理路由滚动

安装vue-router

复制代码
npm install vue-router
  1. 然后,在你的项目中配置 Vue Router。例如,在 src/router/index.js 文件中
复制代码
import Vue from 'vue';  
import VueRouter from 'vue-router';  
import Home from '../views/Home.vue';  
import About from '../views/About.vue';  
  
Vue.use(VueRouter);  
  
const routes = [  
  {  
    path: '/',  
    name: 'Home',  
    component: Home  
  },  
  {  
    path: '/about',  
    name: 'About',  
    component: About  
  }  
];  
  
const router = new VueRouter({  
  mode: 'history',  
  base: process.env.BASE_URL,  
  routes  
});  
  
export default router;

3.创建目标组件并添加目标元素

假设我们想在 About.vue 组件中滚动到某个特定的位置。我们可以在 About.vue 中添加一个具有唯一 id属性的元素

复制代码
<template>  
  <div>  
    <h1>About Page</h1>
    <!-- 为了演示滚动效果,添加高度 -->  
    <div style="height: 1000px;"> 
      Scroll down to see the target element.  
    </div>
    <!-- 滚动到目标位置 -->  
    <div id="targetElement">  
      This is the target element.  
    </div>  
  </div>  
</template>  
  
<script>  
export default {  
  name: 'About',  
  mounted() {  
    // 这里可以添加一些组件挂载后的逻辑,但滚动通常是在路由导航守卫中处理  
  }  
};  
</script>  
  
<style scoped>  
/* 添加一些样式以改善视觉效果 */  
</style>

4.在路由导航守卫中处理滚动

为了实现滚动到指定位置,我们需要在路由导航守卫中处理滚动逻辑。可以在 src/router/index.js 中添加滚动行为:

复制代码
import Vue from 'vue';  
import VueRouter from 'vue-router';  
import Home from '../views/Home.vue';  
import About from '../views/About.vue';  
  
Vue.use(VueRouter);  
  
const routes = [  
  {  
    path: '/',  
    name: 'Home',  
    component: Home  
  },  
  {  
    path: '/about',  
    name: 'About',  
    component: About,  
    // 可以在路由配置中添加 meta 字段来存储滚动信息  
    meta: {  
      scrollToTarget: true // 标记该路由需要滚动到目标位置  
    }  
  }  
];  
  
const router = new VueRouter({  
  mode: 'history',  
  base: process.env.BASE_URL,  
  routes,  
  scrollBehavior(to, from, savedPosition) {  
    if (to.meta.scrollToTarget) {  
      return new Promise((resolve, reject) => {  
        setTimeout(() => {
        // 获取目标元素
          const targetElement = document.querySelector('#targetElement');  
          if (targetElement) {
          // 滚动到目标位置  
            targetElement.scrollIntoView({ behavior: 'smooth' });  
          }  
          resolve();  
        }, 0); // 使用 setTimeout 确保 DOM 更新完成  
      });  
    } else {  
      // 如果没有特定要求,则恢复之前的位置或滚动到顶部  
      return savedPosition || { x: 0, y: 0 };  
    }  
  }  
});  
  
export default router;

5.触发路由导航

最后,在你的 Home.vue 或其他组件中触发路由导航:

复制代码
<template>  
  <div>  
    <h1>Home Page</h1>  
    <button @click="goToAbout">Go to About Page</button>  
  </div>  
</template>  
  
<script>  
export default {  
  name: 'Home',  
  methods: {  
    goToAbout() {  
      this.$router.push({ name: 'About' });  
    }  
  }  
};  
</script>

方法2: 在页面中处理滚动至指定位置

  1. 创建 home.vue , about.vue 页面

  2. 在home.vue跳转到about.vue页面

复制代码
this.$router.push({
  path: "/about"
});
  1. 跳转到about页面后,在about页面获取指定元素距离顶部的距离
复制代码
<template>
  <div>
  <!-- 为了演示滚动效果,添加高度 -->
    <div style='height:1000px'>div1</div>
    <div id='div2' class='id2'>div2</div>
  </div>  
</template>
<script> 
export default {
  name: "about",
  mounted() {
    this.setScrolltop();
  },
  methods: {
    setScrolltop(){
      let time=setTimeout(()=>{
          this.$nextTick(()=>{
            let top=0;
            let targetElement=document.getElementById("id2");
            if(targetElement){
            // 获取元素距离顶部的距离
              top=targetElement.offsetTop;
            }
            if(top>0){
            // 滚动到指定位置
              window.scrollTo({
                top: top,
                behavior: 'smooth'
              });
            }
            clearTimeout(time);
            time=null;
          })
        },1000);
    }
  }
} 
</script>
相关推荐
悟能不能悟6 小时前
浏览器执行刷新,都经历过什么阶段
vue
是梦终空1 天前
计算机毕业设计248—基于Java+Springboot+vue的博物馆预约系统(源代码+数据库+开发文档)
java·spring boot·vue·毕业设计·jwt·博物馆预约系统·博物馆网站
我命由我123451 天前
微信小程序 - scroll-view 的一些要点(scroll-view 需要设置滚动方向、scroll-view 需要设置高度)
开发语言·前端·javascript·微信小程序·小程序·前端框架·js
@AfeiyuO1 天前
Vue 全局引用iconfon
vue
吳所畏惧1 天前
少走弯路:uniapp里将h5链接打包为apk,并设置顶/底部安全区域自动填充显示,阻止webview默认全屏化
android·安全·uni-app·json·html5·webview·js
@AfeiyuO1 天前
多层环形图,自定义tooltip
vue·echarts
JIngJaneIL1 天前
基于Java失物招领系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·vue
by__csdn1 天前
ES6新特性全攻略:JavaScript的现代革命
开发语言·前端·javascript·typescript·ecmascript·es6·js
by__csdn1 天前
Vue 双向数据绑定深度解析:从原理到实践的全方位指南
前端·javascript·vue.js·typescript·前端框架·vue·ecmascript
苏打水com1 天前
第六篇:Day16-18 AJAX进阶+接口对接——实现“前后端数据交互”(对标职场“接口开发”核心需求)
css·okhttp·html·js