diff --git a/examples/keepalive-view/app.js b/examples/keepalive-view/app.js index ced1f9691..2155782b8 100644 --- a/examples/keepalive-view/app.js +++ b/examples/keepalive-view/app.js @@ -12,10 +12,20 @@ const Index = { } } -const IndexChild1 = { template: '
index child1
' } -const IndexChild2 = { template: '
index child2
' } +const WithGuard = { + template: '
{{ $route.name }}: {{ n }}
', + data: () => ({ n: 0 }), + beforeRouteEnter (to, from, next) { + next(vm => { + vm.n++ + }) + } +} -const Home = { template: '
home
' } +const IndexChild1 = { template: '
index child1
' } +const IndexChild2 = { template: '
index child2
' } + +const Home = { template: '
home
' } const router = new VueRouter({ mode: 'history', @@ -38,6 +48,16 @@ const router = new VueRouter({ { path: '/home', component: Home + }, + { + path: '/with-guard1', + name: 'with-guard1', + component: WithGuard + }, + { + path: '/with-guard2', + name: 'with-guard2', + component: WithGuard } ] }) @@ -47,12 +67,14 @@ new Vue({ template: `
- +
` diff --git a/src/components/view.js b/src/components/view.js index a3c8a0319..3f440d5b4 100644 --- a/src/components/view.js +++ b/src/components/view.js @@ -72,6 +72,17 @@ export default { matched.instances[name] = vnode.componentInstance } + // register instance in init hook + // in case kept-alive component be actived when routes changed + data.hook.init = (vnode) => { + if (vnode.data.keepAlive && + vnode.componentInstance && + vnode.componentInstance !== matched.instances[name] + ) { + matched.instances[name] = vnode.componentInstance + } + } + // resolve props let propsToPass = data.props = resolveProps(route, matched.props && matched.props[name]) if (propsToPass) { diff --git a/test/e2e/specs/keepalive-view.js b/test/e2e/specs/keepalive-view.js index 7e68ada41..2de35e5f6 100644 --- a/test/e2e/specs/keepalive-view.js +++ b/test/e2e/specs/keepalive-view.js @@ -3,20 +3,30 @@ module.exports = { browser .url('http://localhost:8080/keepalive-view/') .waitForElementVisible('#app', 1000) - .assert.count('li a', 3) + .assert.count('li a', 5) .click('li:nth-child(1) a') - .assert.containsText('.current', 'index child1') + .assert.containsText('.view', 'index child1') .click('li:nth-child(2) a') - .assert.containsText('.current', 'index child2') + .assert.containsText('.view', 'index child2') .click('li:nth-child(3) a') - .assert.containsText('.current', 'home') + .assert.containsText('.view', 'home') // back to index child1 and check it .click('li:nth-child(1) a') - .assert.containsText('.current', 'index child1') + .assert.containsText('.view', 'index child1') + + // beforeRouteEnter guard with keep alive + // https://github.com/vuejs/vue-router/issues/2561 + .click('li:nth-child(4) a') + .assert.containsText('.view', 'with-guard1: 1') + .click('li:nth-child(5) a') + .assert.containsText('.view', 'with-guard2: 2') + .click('li:nth-child(4) a') + .assert.containsText('.view', 'with-guard1: 3') + .end() } }