Issues with link anchor and transition
Vuejs issue with anchor link and transition
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<p>
<router-link to="/home">Home</router-link>
<router-link to="/post#post1">Post 1</router-link>
<router-link to="/post#post2">Post 2</router-link>
</p>
<transition name="fade" mode="out-in">
<router-view></router-view>
</transition>
</div>
CSS
.fade-enter-active, .fade-leave-active{
transition: all .2s ease
}
.fade-enter, .fade-leave-active{
opacity: 0;
}
Babel + JSX
const Home = { template: '<div>Home</div>' }
const Post = { template: '<div>Post <p style="margin-top:800px" id="post1">post 1 </p> <p style="margin-top:800px" id="post2">post 2 </p> </div>' }
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 0
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}
}
const router = new VueRouter({
mode: 'history',
scrollBehavior,
routes: [
{ path: '/home', component: Home },
{ path: '/post', component: Post }
]
})
const app = new Vue({ router }).$mount('#app')