官方文档
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const Home = { template: '<div>home</div>' }
const Foo = { template: '<div>foo</div>' }
const Bar = {
template: `
<div>
bar
<div style="height:500px"></div>
<p id="anchor">Anchor</p>
</div>
`
}
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {//返回之前的原位置
// savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。
return savedPosition
} else {
const position = {}
if (to.hash) {//如果路径中有哈希值,就采用锚点定位
position.selector = to.hash
}
if (to.matched.some(m => m.meta.scrollToTop)) {//如果路由元信息中存在参数,对参数做进一步判断(此示例代表滚动到顶部)
position.x = 0
position.y = 0
}
//如果返回一个 falsy (假的值),或者是一个空对象,那么不会发生滚动。
return position
}
}
const router = new VueRouter({
mode: 'history',
base: __dirname,
scrollBehavior,
routes: [
{ path: '/', component: Home, meta: { scrollToTop: true }},
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar, meta: { scrollToTop: true }}
]
})
new Vue({
router,
template: `
<div id="app">
<h1>Scroll Behavior</h1>
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/foo">/foo</router-link></li>
<li><router-link to="/bar">/bar</router-link></li>
<li><router-link to="/bar#anchor">/bar#anchor</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>
`
}).$mount('#app')