vue2.0 v

您所在的位置:网站首页 button按钮跳转到指定页面 vue2.0 v

vue2.0 v

2023-06-24 05:22| 来源: 网络整理| 查看: 265

1.在 Vue 中点击跳转页面到指定位置,你可以使用 Vue Router 和 scrollBehavior 方法来实现。首先,在router/index.js文件中,你需要配置scrollBehavior方法来处理页面跳转时的滚动行为。这个方法会在每次路由切换时被调用。

import Vue from 'vue' import VueRouter from 'vue-router' import HomeView from '../views/HomeView.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'home', component: HomeView }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') } ] const router = new VueRouter({ mode: "history", routes, scrollBehavior(to, from, savedPosition) { // 如果有指定的滚动位置,则直接滚动到指定位置 if (to.hash) { return { selector: to.hash } } // 否则滚动到顶部 return { x: 0, y: 0 } } }) export default router

2.接下来,在模板文件中的链接中添加 to 属性,并使用对象格式指定路由路径和滚动位置,例如:

{{item.ct}} // @ is an alias to /src export default { name: 'HomeView', data(){ return{ yemian:[ { path:'about', hash: '#section1', ct:'跳转到指定位置1' }, { path:'about', hash: '#section2', ct:'跳转到指定位置2' } ] } }, components: { }, methods:{ tiaozhuan(item){ this.$router.push({path: item.path,hash:item.hash}) } } }

在上述代码中,我们使用了 router-link 组件来生成具有指定路径的链接,使用对象格式的 to 属性来指定路径和滚动位置。点击链接时,Vue Router 将会自动处理路由跳转和滚动到指定位置的行为。

3.在跳转时,hash 属性表示需要滚动到页面中对应的元素的 id。在跳转到页面后,可以在对应页面的 mounted 钩子中调用 scrollTo() 方法,来实现滚动到指定的元素位置:

位置1 位置2 export default { mounted() { if (this.$route.hash) { this.scrollToElement(this.$route.hash.slice(1)); } }, methods: { scrollToElement(id) { const element = document.getElementById(id); if (element) { element.scrollIntoView({ behavior: "smooth", }); } }, }, };

这样就完成啦(*^▽^*)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3