@@ -3,11 +3,11 @@ import VueRouter from 'vue-router'
33
44Vue . use ( VueRouter )
55
6- const Home = { template : '<div>home</div>' }
7- const Foo = { template : '<div>foo</div>' }
6+ const Home = { template : '<div class="home" >home</div>' }
7+ const Foo = { template : '<div class="foo" >foo</div>' }
88const Bar = {
99 template : `
10- <div>
10+ <div class="bar" >
1111 bar
1212 <div style="height:500px"></div>
1313 <p id="anchor" style="height:500px">Anchor</p>
@@ -20,32 +20,42 @@ const Bar = {
2020// - only available in html5 history mode
2121// - defaults to no scroll behavior
2222// - return false to prevent scroll
23- const scrollBehavior = ( to , from , savedPosition ) => {
23+ const scrollBehavior = function ( to , from , savedPosition ) {
2424 if ( savedPosition ) {
2525 // savedPosition is only available for popstate navigations.
2626 return savedPosition
2727 } else {
28- const position = { }
29- // new navigation.
30- // scroll to anchor by returning the selector
31- if ( to . hash ) {
32- position . selector = to . hash
28+ return new Promise ( resolve => {
29+ const position = { }
30+ let delay = 500
31+ // new navigation.
32+ // scroll to anchor by returning the selector
33+ if ( to . hash ) {
34+ position . selector = to . hash
3335
34- // specify offset of the element
35- if ( to . hash === '#anchor2' ) {
36- position . offset = { y : 100 }
36+ // specify offset of the element
37+ if ( to . hash === '#anchor2' ) {
38+ position . offset = { y : 100 }
39+ }
40+
41+ if ( document . querySelector ( to . hash ) ) {
42+ delay = 0
43+ }
44+ }
45+ // check if any matched route config has meta that requires scrolling to top
46+ if ( to . matched . some ( m => m . meta . scrollToTop ) ) {
47+ // coords will be used if no selector is provided,
48+ // or if the selector didn't match any element.
49+ position . x = 0
50+ position . y = 0
3751 }
38- }
39- // check if any matched route config has meta that requires scrolling to top
40- if ( to . matched . some ( m => m . meta . scrollToTop ) ) {
41- // cords will be used if no selector is provided,
42- // or if the selector didn't match any element.
43- position . x = 0
44- position . y = 0
45- }
46- // if the returned position is falsy or an empty object,
47- // will retain current scroll position.
48- return position
52+ // wait for the out transition to complete (if necessary)
53+ setTimeout ( ( ) => {
54+ // if the returned position is falsy or an empty object,
55+ // will retain current scroll position.
56+ resolve ( position )
57+ } , delay )
58+ } )
4959 }
5060}
5161
@@ -72,7 +82,9 @@ new Vue({
7282 <li><router-link to="/bar#anchor">/bar#anchor</router-link></li>
7383 <li><router-link to="/bar#anchor2">/bar#anchor2</router-link></li>
7484 </ul>
75- <router-view class="view"></router-view>
85+ <transition name="fade" mode="out-in">
86+ <router-view class="view"></router-view>
87+ </transition>
7688 </div>
7789 `
7890} ) . $mount ( '#app' )
0 commit comments