vue-cli项目中如何使用锚点
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
vue-cli项⽬中如何使⽤锚点两种⽅式:
1.使⽤vue-router实现锚点功能(利⽤html5的history模式,vue-router的滚动⾏为)
1 import Vue from 'vue'
2 import VueRouter from 'vue-router'
3
4 e(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) => {
23if (savedPosition) {
24// savedPosition is only available for popstate navigations.
25return savedPosition
26 } else {
27 const position = {}
28// new navigation.
29// scroll to anchor by returning the selector
30if (to.hash) {
31 position.selector = to.hash
32 }
33// check if any matched route config has meta that requires scrolling to top
34if (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.
42return 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
57new 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')
View Code
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) {
10var 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')
View Code。