- This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
Component_dynamic Component
The basic use
When we are in a multi-tab interface, it is very useful to dynamically switch between different components.
<div id="app">
<button
v-for="page in pages"
@click="pageCmp = page.cmp"
:key="page.id"
>{{ page.name }}</button>
<component :is="pageCmp"></component>
</div>
Copy the code
Vue.component('base-post', {
data () {
return {
postCmp: ' '.posts: [{title: "Heading 1".content: { template: Content of ` < div > 1 < / div > `}, id: 11},
{ title: "Heading 2".content: { template: Content of ` < div > 2 < / div > `}, id: 12},
{ title: "Title".content: { template: Content of ` < div > 3 < / div > `}, id: 13},
],
}
},
mounted () {
this.postCmp = this.posts[0].content;
},
template: `
`
})
Vue.component('base-more', {
template: '
More
})
const vm = new Vue({
el: '#app'.data: {
pages: [{name: 'blog'.cmp: 'base-post'.id: 0},
{ name: 'more'.cmp: 'base-more'.id: 1}].pageCmp: 'base-post'}})Copy the code
By the above method, we can realize the switch between components, to be able to notice is that every time a switch label, will create a new component instance, to create the dynamic component in more cases are very useful, but in this case, we will be more hope what label component instance can be created for the first time in their cache down. To solve this problem, we can wrap the dynamic component with a
element. Such as:
<! -- Deactivated components will be cached! -->
<keep-alive>
<component v-bind:is="pageCmp"></component>
</keep-alive>
Copy the code
Note:
requires that the component being switched to have its own name, either through the component’s name option or through local/global registration.
keep-alive
when wrapping dynamic components, inactive component instances are cached rather than destroyed.
is an abstract component: it does not render a DOM element on its own and does not appear in the parent component chain. When a component is switched within
, its activated and deactivated lifecycle hook functions are executed accordingly.
activated & deactivated
Activated: activated when the keep-alive component is activated. Deactivated: Activated when the keep-alive component is disabled.
The last
If it is helpful to you, I hope to give you a 👍 comment/collection/three even!
Bloggers are honest and answer questions for free ❤