Vue 学习笔记(十二):动态组件 & 异步组件

动态组件 & 异步组件
Dynamic & Async Components

在动态组件上使用 keep-alive

《Vue 学习笔记(七):组件基础》提到一个多标签的界面中使用 is attribute 来切换不同的组件:

1
<component v-bind:is="currentTabComponent"></component>

在这些组件之间切换,有时需要保持这些组件的状态,以避免反复重渲染。示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<script src="https://unpkg.com/vue"></script>

<div id="dynamic-component-demo" class="demo">
<button
v-for="tab in tabs"
v-bind:key="tab"
v-bind:class="['dynamic-component-demo-tab-button', { 'dynamic-component-demo-active': currentTab === tab }]"
v-on:click="currentTab = tab"
>{{ tab }}</button>
<component
v-bind:is="currentTabComponent"
class="dynamic-component-demo-tab"
></component>
</div>
<script>
Vue.component('tab-posts', {
data: function () {
return {
posts: [
{
id: 1,
title: 'Cat Ipsum',
content: '<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>'
},
{
id: 2,
title: 'Hipster Ipsum',
content: '<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>'
},
{
id: 3,
title: 'Cupcake Ipsum',
content: '<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>'
}
],
selectedPost: null
}
},
template: '\
<div class="dynamic-component-demo-posts-tab">\
<ul class="dynamic-component-demo-posts-sidebar">\
<li\
v-for="post in posts"\
v-bind:key="post.id"\
v-bind:class="{ \'dynamic-component-demo-active\': post === selectedPost }"\
v-on:click="selectedPost = post"\
>\
{{ post.title }}\
</li>\
</ul>\
<div class="dynamic-component-demo-post-container">\
<div \
v-if="selectedPost"\
class="dynamic-component-demo-post"\
>\
<h3>{{ selectedPost.title }}</h3>\
<div v-html="selectedPost.content"></div>\
</div>\
<strong v-else>\
Click on a blog title to the left to view it.\
</strong>\
</div>\
</div>\
'
})
Vue.component('tab-archive', {
template: '<div>Archive component</div>'
})
new Vue({
el: '#dynamic-component-demo',
data: {
currentTab: 'Posts',
tabs: ['Posts', 'Archive']
},
computed: {
currentTabComponent: function () {
return 'tab-' + this.currentTab.toLowerCase()
}
}
})
</script>
<style>
.dynamic-component-demo-tab-button {
padding: 6px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ccc;
cursor: pointer;
background: #f0f0f0;
margin-bottom: -1px;
margin-right: -1px;
}
.dynamic-component-demo-tab-button:hover {
background: #e0e0e0;
}
.dynamic-component-demo-tab-button.dynamic-component-demo-active {
background: #e0e0e0;
}
.dynamic-component-demo-tab {
border: 1px solid #ccc;
padding: 10px;
}
.dynamic-component-demo-posts-tab {
display: flex;
}
.dynamic-component-demo-posts-sidebar {
max-width: 40vw;
margin: 0 !important;
padding: 0 10px 0 0 !important;
list-style-type: none;
border-right: 1px solid #ccc;
}
.dynamic-component-demo-posts-sidebar li {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
cursor: pointer;
}
.dynamic-component-demo-posts-sidebar li:hover {
background: #eee;
}
.dynamic-component-demo-posts-sidebar li.dynamic-component-demo-active {
background: lightblue;
}
.dynamic-component-demo-post-container {
padding-left: 10px;
}
.dynamic-component-demo-post > :first-child {
margin-top: 0 !important;
padding-top: 0 !important;
}
</style>

渲染结果:

如果选择了一篇文章,切换到 Archive 标签,然后再切换回 Posts,是不会继续展示之前选择的文章的。这是因为每次切换新标签的时候,Vue 都创建了一个新的 currentTabComponent 实例。

重新创建动态组件的行为通常是非常有用的,但是在这个案例中,我们更希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。对此,可以用一个 <keep-alive> 元素将其动态组件包裹起来。

1
2
3
4
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>

修改后的源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<script src="https://unpkg.com/vue"></script>
<div id="dynamic-component-demo" class="demo">
<button
v-for="tab in tabs"
v-bind:key="tab"
v-bind:class="['dynamic-component-demo-tab-button', { 'dynamic-component-demo-active': currentTab === tab }]"
v-on:click="currentTab = tab"
>{{ tab }}</button>
<component
v-bind:is="currentTabComponent"
class="dynamic-component-demo-tab"
></component>
</div>
<script>
Vue.component('tab-posts', {
data: function () {
return {
posts: [
{
id: 1,
title: 'Cat Ipsum',
content: '<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>'
},
{
id: 2,
title: 'Hipster Ipsum',
content: '<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>'
},
{
id: 3,
title: 'Cupcake Ipsum',
content: '<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>'
}
],
selectedPost: null
}
},
template: '\
<div class="dynamic-component-demo-posts-tab">\
<ul class="dynamic-component-demo-posts-sidebar">\
<li\
v-for="post in posts"\
v-bind:key="post.id"\
v-bind:class="{ \'dynamic-component-demo-active\': post === selectedPost }"\
v-on:click="selectedPost = post"\
>\
{{ post.title }}\
</li>\
</ul>\
<div class="dynamic-component-demo-post-container">\
<div \
v-if="selectedPost"\
class="dynamic-component-demo-post"\
>\
<h3>{{ selectedPost.title }}</h3>\
<div v-html="selectedPost.content"></div>\
</div>\
<strong v-else>\
Click on a blog title to the left to view it.\
</strong>\
</div>\
</div>\
'
})
Vue.component('tab-archive', {
template: '<div>Archive component</div>'
})
new Vue({
el: '#dynamic-component-demo',
data: {
currentTab: 'Posts',
tabs: ['Posts', 'Archive']
},
computed: {
currentTabComponent: function () {
return 'tab-' + this.currentTab.toLowerCase()
}
}
})
</script>
<style>
.dynamic-component-demo-tab-button {
padding: 6px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ccc;
cursor: pointer;
background: #f0f0f0;
margin-bottom: -1px;
margin-right: -1px;
}
.dynamic-component-demo-tab-button:hover {
background: #e0e0e0;
}
.dynamic-component-demo-tab-button.dynamic-component-demo-active {
background: #e0e0e0;
}
.dynamic-component-demo-tab {
border: 1px solid #ccc;
padding: 10px;
}
.dynamic-component-demo-posts-tab {
display: flex;
}
.dynamic-component-demo-posts-sidebar {
max-width: 40vw;
margin: 0 !important;
padding: 0 10px 0 0 !important;
list-style-type: none;
border-right: 1px solid #ccc;
}
.dynamic-component-demo-posts-sidebar li {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
cursor: pointer;
}
.dynamic-component-demo-posts-sidebar li:hover {
background: #eee;
}
.dynamic-component-demo-posts-sidebar li.dynamic-component-demo-active {
background: lightblue;
}
.dynamic-component-demo-post-container {
padding-left: 10px;
}
.dynamic-component-demo-post > :first-child {
margin-top: 0 !important;
padding-top: 0 !important;
}
</style>

渲染结果:

现在 Posts 标签保持了它的状态 (被选中的文章) 甚至当它未被渲染时也是如此。

注意 <keep-alive> 要求被切换到的组件都有自己的名字,无论是通过组件的 name 选项还是局部/全局注册。

异步组件 Async Components

在大型应用中,可能需要将应用分割成小一些的代码块,并且只在需要的时候才从服务器加载一个模块。为了简化,Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染。例如:

1
2
3
4
5
6
7
8
Vue.component('async-example', function (resolve, reject) {
setTimeout(function () {
// 向 `resolve` 回调传递组件定义
resolve({
template: '<div>I am async!</div>'
})
}, 1000)
})

这个工厂函数会收到一个 resolve 回调,该回调函数会在你从服务器得到组件定义的时候被调用。也可以调用 reject(reason) 来表示加载失败。这里的 setTimeout 是为了演示用的,如何获取组件取决于你自己。一个推荐的做法是将异步组件和 webpack 的 code-splitting 功能一起配合使用:

1
2
3
4
5
6
Vue.component('async-webpack-example', function (resolve) {
// 这个特殊的 `require` 语法将会告诉 webpack
// 自动将你的构建代码切割成多个包,这些包
// 会通过 Ajax 请求加载
require(['./my-async-component'], resolve)
})

也可以在工厂函数中返回一个 Promise,把 webpack 2 和 ES2015 语法加在一起,可以这样使用动态导入:

1
2
3
4
5
Vue.component(
'async-webpack-example',
// 这个动态导入会返回一个 `Promise` 对象。
() => import('./my-async-component')
)

当使用 局部注册 的时候,也可以直接提供一个返回 Promise 的函数:

1
2
3
4
5
6
new Vue({
// ...
components: {
'my-component': () => import('./my-async-component')
}
})

处理加载状态 Handling Loading State

这里的异步组件工厂函数也可以返回一个如下格式的对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
const AsyncComponent = () => ({
// 需要加载的组件 (应该是一个 `Promise` 对象)
component: import('./MyComponent.vue'),
// 异步组件加载时使用的组件
loading: LoadingComponent,
// 加载失败时使用的组件
error: ErrorComponent,
// 展示加载时组件的延时时间。默认值是 200 (毫秒)
delay: 200,
// 如果提供了超时时间且组件加载也超时了,
// 则使用加载失败时使用的组件。默认值是:`Infinity`
timeout: 3000
})