# 文档初探(九): 动态&异步组件
# keep-alive
我们在做 tab 切换时, 如果想保留切换前的状态, 可以使用<keep-alive></keep-alive>
包裹住组件
# 异步组件
一些组件不会在一开始就加载完. 会等待用户触发一些操作才会去向服务端请求, 这些组件就是异步组件.
# 异步组件的第一种写法
Vue.component("async-example", (resolve, reject) => { setTimeout(() => { resolve({ template: `<div>I am async</div>` }); }, 3000); }); new Vue({ el: "#app", template: ` <div> <async-example /> {{n}} </div> `, data() { return { n: "3秒后出现" }; } });
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 第二种异步组件的写法
// 全局注册 Vue.component( "async-webpack-example", // The `import` function returns a Promise. () => import("./my-async-component") ); // 局部注册 new Vue({ // ... components: { "my-component": () => import("./my-async-component") } });
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14