File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ # 惰性加载 lazy load
2+
3+ 当你在使用 Webpack 或者 Browserify 时,在基于[ 异步组件] ( http://vuejs.org/guide/components.html#Async_Components ) 编写的 Vue 项目时,也可以较为容易的实现惰性加载组件。不再是之前所述的直接引用一个组件,现在需要像下面这样通过定义一个函数返回一个组件:
4+
5+
6+ ``` js
7+ router .map ({
8+ ' /async' : {
9+ component : function (resolve ) {
10+ // somehow retrieve your component definition from server...
11+ resolve (MyComponent)
12+ }
13+ }
14+ })
15+ ```
16+
17+ 现在,手动引入组件并不理想,有幸 Webpack 和 Browserify 都提供了简单的解决方案。
18+
19+ ### Webpack
20+
21+ Webpack 已经集成了代码分割功能。你可以使用 AMD 风格的 ` require ` 来对你的代码标识代码分割点:
22+
23+ ``` js
24+ require ([' ./MyComponent.vue' ], function (MyComponent ) {
25+ // code here runs after MyComponent.vue is asynchronously loaded.
26+ })
27+ ```
28+
29+ 和路由配合使用,如下:
30+
31+ ``` js
32+ router .map ({
33+ ' /async' : {
34+ component : function (resolve ) {
35+ require ([' ./MyComponent.vue' ], resolve)
36+ }
37+ }
38+ })
39+ ```
40+
41+ 现在,只有当 ` /async ` 需要被渲染时,` MyComponent.vue ` 组件,会自动加载它的依赖组件,并且异步的加载进来。
42+
43+ ### Browserify
44+
45+ 使用 Browserify 还需要一些技巧。你可能需要插件 [ ` partition-bundle ` ] ( https://github.com/substack/browserify-handbook/blob/master/readme.markdown#partition-bundle ) ,并且需要在 ` json ` 文件中手动声明:
46+
47+ ``` json
48+ {
49+ "main.js" : [" ./main.js" ],
50+ "my-component.js" : [" ./MyComponent.vue" ]
51+ }
52+ ```
53+
54+ 然后在 ` main.js ` ,你需要做一些类似的操作,用 ` loadjs ` 替代 ` require ` :
55+
56+ ``` js
57+ router .map ({
58+ ' /async' : {
59+ component : function (resolve ) {
60+ loadjs ([' ./MyComponent.vue' ], resolve)
61+ }
62+ }
63+ })
64+ ```
You can’t perform that action at this time.
0 commit comments