console
Vue.component('CompA', {
template:
`<div>
<div>
CompA
<button @click="changeNum">切换序号</button>
</div>
<div v-show="currentNum == 1">1</div>
<div v-show="currentNum == 2">2</div>
</div>`,
data() {
return {
currentNum: 1
}
},
methods: {
changeNum() {
this.currentNum = this.currentNum == 1 ? 2 : 1;
}
}
});
Vue.component('CompB', {
template: `<div>CompB</div>`
});
const vm = new Vue({
el: '#app',
data: {
currentComp: 'CompA'
},
methods: {
changeComp() {
if (this.currentComp === 'CompA') {
this.currentComp = 'CompB';
} else {
this.currentComp = 'CompA';
}
}
}
});
<div id="app">
<h3>动态组件使用keep-alive</h3>
<keep-alive>
<component :is="currentComp"></component>
</keep-alive>
<h3>普通组件使用keep-alive</h3>
<keep-alive>
<comp-a></comp-a>
</keep-alive>
<h3>普通动态组件</h3>
<component :is="currentComp"></component>
<button @click="changeComp">切换组件</button>
</div>