两种方式:
1.使用vue-router实现锚点功能(利用html5的history模式,vue-router的滚动行为)
1 import Vue from 'vue' 2 import VueRouter from 'vue-router' 3 4 Vue.use(VueRouter) 5 6 const Home = { template: '<div>home</div>' } 7 const Foo = { template: '<div>foo</div>' } 8 const Bar = { 9 template: ` 10 <div> 11 bar 12 <div style="height:500px"></div> 13 <p id="anchor">Anchor</p> 14 </div> 15 ` 16 } 17 18 // scrollBehavior: 19 // - only available in html5 history mode 20 // - defaults to no scroll behavior 21 // - return false to prevent scroll 22 const scrollBehavior = (to, from, savedPosition) => { 23 if (savedPosition) { 24 // savedPosition is only available for popstate navigations. 25 return savedPosition 26 } else { 27 const position = {} 28 // new navigation. 29 // scroll to anchor by returning the selector 30 if (to.hash) { 31 position.selector = to.hash 32 } 33 // check if any matched route config has meta that requires scrolling to top 34 if (to.matched.some(m => m.meta.scrollToTop)) { 35 // cords will be used if no selector is provided, 36 // or if the selector didn't match any element. 37 position.x = 0 38 position.y = 0 39 } 40 // if the returned position is falsy or an empty object, 41 // will retain current scroll position. 42 return position 43 } 44 } 45 46 const router = new VueRouter({ 47 mode: 'history', 48 base: __dirname, 49 scrollBehavior, 50 routes: [ 51 { path: '/', component: Home, meta: { scrollToTop: true }}, 52 { path: '/foo', component: Foo }, 53 { path: '/bar', component: Bar, meta: { scrollToTop: true }} 54 ] 55 }) 56 57 new Vue({ 58 router, 59 template: ` 60 <div id="app"> 61 <h1>Scroll Behavior</h1> 62 <ul> 63 <li><router-link to="/">/</router-link></li> 64 <li><router-link to="/foo">/foo</router-link></li> 65 <li><router-link to="/bar">/bar</router-link></li> 66 <li><router-link to="/bar#anchor">/bar#anchor</router-link></li> 67 </ul> 68 <router-view class="view"></router-view> 69 </div> 70 ` 71 }).$mount('#app')
2.在无法使用history模式的情况下,使用另外一种方式:
1 const Foo = { 2 template: ` 3 <div> 4 <div><a href="javascript:void(0)" @click="goAnchor('#anchor-'+index)" v-for="index in 20"> {{index}} </a></div> 5 <div :id="'anchor-'+index" class="item" v-for="index in 20">{{index}}</div> 6 </div> 7 `, 8 methods: { 9 goAnchor(selector) { 10 var anchor = this.$el.querySelector(selector) 11 document.body.scrollTop = anchor.offsetTop 12 } 13 } 14 } 15 const Bar = { 16 template: '<div>bar</div>' 17 } 18 19 const routes = [ 20 { path: '/foo', component: Foo }, 21 { path: '/bar', component: Bar } 22 ] 23 24 const router = new VueRouter({ 25 routes, 26 }) 27 28 const app = new Vue({ 29 router 30 }).$mount('#app')