{{item.name}}
</router-link>
</div>
</div>
<div style="flex: 1;overflow: scroll;">
<div v-for="item in list" :key="item.id">
<router-link style="line-height: 100px;display:block;" :to="{ name: 'Detail', params: { id: item.id } }">
{{item.name}}
</router-link>
</div>
</div>
</div>`,
data() {
return {
list: new Array(10).fill(1).map((_,index) => {
return {id: index + 1, name: `item${index + 1}`};
}),
};
},
mounted() {
console.warn('List', 'mounted');
},
activated() {
console.warn('List', 'activated');
},
deactivated() {
console.warn('List', 'deactivated');
},
};
const Detail = {
name: 'Detail',
template:
`<div>
详情页
<div>
{{$route.params.id}}
</div>
</div>`,
mounted() {
console.warn('Detail', 'mounted');
},
};
const routes = [
{ path: '', name: 'Main', component: Index },
{ path: '/list', name: 'List', component: List },
{ path: '/detail/:id', name: 'Detail', component: Detail },
];
const router = new VueRouter({
routes,
});
const app = new Vue({
router,
}).$mount('#app');
当我们第一次从首页进入列表页时, mounted 和 activated 将被先后触发,而在此后无论是进入详情页再回退,或是回退到首页再进入列表页,都只会触发 deactivated 生命周期。
keep-alive
includes
keep-alive有一个 includes 选项,这个选项可以接受一个数组,并通过这个数组来决定组件的保活状态:
// keep-alive
render () {
const slot = this.$slots.default
const vnode: VNode = getFirstComponentChild(slot)
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
const name: ?string = getComponentName(componentOptions)
const { include, exclude } = this
if (
(include && (!name || !matches(include, name))) ||
(exclude && name && matches(exclude, name))
) {
return vnode
} const { cache, keys } = this
const key: ?string = vnode.key == null
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance
remove(keys, key)
keys.push(key)
} else {
cache[key] = vnode
keys.push(key)
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true










