踩坑记录:
v-bind:is
来动态传入模板并缓存它们
在这个例子中,我们有两个按钮来切换currentComponent
的值,currentComponent
的值会被绑定到<component>
元素的is
属性上。通过改变currentComponent
的值,你可以动态地在页面上显示不同的组件。
注意,为了确保组件能够正确地被缓存,使用了:key
属性绑定到<component>
元素上,这个key与当前激活的组件的名称相同。这确保了每次切换时,如果组件存在,它会被复用而不是重新创建。
如果发现切换到其他页面后再切换回来还是没缓存,可检查下 路由name跟当面页面得name是否一致。要保持一致
<template>
<div>
<button @click="currentComponent = 'ComponentA'">显示组件A</button>
<button @click="currentComponent = 'ComponentB'">显示组件B</button>
<component :is="currentComponent" :key="currentComponent"></component>
</div>
</template>
<script>
export default {
name:'name1', // 要与路由name:'name1'一致
data() {
return {
currentComponent: 'ComponentA'
};
},
components: {
ComponentA: {
template: '<div>组件A的内容</div>',
// 其他选项...
},
ComponentB: {
template: '<div>组件B的内容</div>',
// 其他选项...
}
// 可以根据需要添加更多的组件
}
};
</script>