两种方式:

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 >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 >
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')
View Code

相关文章: