重用组件时如何触发转换?
Posted
技术标签:
【中文标题】重用组件时如何触发转换?【英文标题】:How to trigger a transition when a component is reused? 【发布时间】:2017-02-13 20:30:35 【问题描述】:在同一个组件之间切换时如何触发切换?
(对于 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');
<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>
【问题讨论】:
【参考方案1】:在router-view
上使用key
参数。
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>
【讨论】:
你应该使用组件模板中 中的 key 属性(例如:jsfiddle.net/Atinux/dv0u80Lc) @Atinux 有什么区别/最佳实践:路由器或组件内主 div 上的关键属性? (在组件上,它不会更新组件的数据) 你救了我。以上是关于重用组件时如何触发转换?的主要内容,如果未能解决你的问题,请参考以下文章