如何在同一组件之间转换时触发转换?
(使用vue-router 1,有一个canReuse
挂钩。它在vue-router 2中不再存在。)
const Index = {
template: `<div id="app">
<router-link :to="{ path: '1' }">page 1</router-link> |
<router-link :to="{ path: '2' }">page 2</router-link>
<router-view></router-view>
</div>`
};
const Page = {
template: `<transition @enter="transitionEnter" @leave="transitionLeave">
<div>
<p>page {{ id }}</p>
</div>
</transition>`,
data() {
return {
id: this.$route.params.id,
}
},
methods: {
transitionEnter(el, done) {
console.log('transitionEnter');
done();
},
transitionLeave(el, done) {
console.log('transitionLeave');
done();
},
fetchData() {
this.id = this.$route.params.id;
}
},
watch: {
'$route': 'fetchData'
},
};
const App = Vue.extend(Index);
const router = new VueRouter({
routes: [{
path: '/:id',
component: Page
}, {
path: '*',
redirect: '/1'
}]
})
const app = new App({ router }).$mount('#app');
&#13;
<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"></div>
&#13;
答案 0 :(得分:6)
使用key
上的router-view
参数。
const Index = {
template: `<div id="app">
<p>app</p>
<router-link :to="{ path: '1' }">page 1</router-link> |
<router-link :to="{ path: '2' }">page 2</router-link>
<router-view :key="'a' + $route.params.id"></router-view>
</div>`
};
const Page = {
template: `<transition @enter="transitionEnter" @leave="transitionLeave">
<div>
<p>page {{ id }}</p>
</div>
</transition>`,
data() {
return {
id: this.$route.params.id,
}
},
methods: {
transitionEnter(el, done) {
console.log('transitionEnter');
done();
},
transitionLeave(el, done) {
console.log('transitionLeave');
done();
},
},
};
const App = Vue.extend(Index);
const router = new VueRouter({
routes: [{
path: '/:id',
component: Page
}, {
path: '*',
redirect: '/1'
}]
})
const app = new App({ router }).$mount('#app');
<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"></div>