File tree Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : 插件
3
+ type : guide
4
+ order : 18
5
+ ---
6
+
7
+ ## 开发插件
8
+
9
+
10
+ 插件通常会为Vue添加全局功能。插件的范围没有限制--一般有下面几种:
11
+
12
+ 1 . 添加全局方法或者属性,如: [ vue-element] ( https://github.com/vuejs/vue-element )
13
+
14
+ 2 . 添加全局资源:指令/过滤器/过渡等。如 vue-touch [ vue-touch] ( https://github.com/vuejs/vue-touch )
15
+
16
+ 3 . 通过全局 mixin方法 添加一些组件选项。 如: [ vuex] ( https://github.com/vuejs/vuex )
17
+
18
+ 4 . 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
19
+
20
+ 5 . A一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 [ vue-router] ( https://github.com/vuejs/vue-router )
21
+
22
+ Vue.js 的插件应当有一个公开方法 ` install ` 。这个方法的第一个参数是 ` Vue ` 构造器 , 第二个参数是一个可选的选项对象:
23
+
24
+ ``` js
25
+ MyPlugin .install = function (Vue , options ) {
26
+ // 1. 添加全局方法或属性
27
+ Vue .myGlobalMethod = function () {
28
+ // something logic ...
29
+ }
30
+
31
+ // 2. 添加全局资源
32
+ Vue .directive (' my-directive' , {
33
+ bind (el , binding , vnode , oldVnode ) {
34
+ // something logic ...
35
+ }
36
+ ...
37
+ })
38
+
39
+ // 3. 注入组件
40
+ Vue .mixin ({
41
+ created : function () {
42
+ // something logic ...
43
+ }
44
+ ...
45
+ })
46
+
47
+ // 4. 添加事例方法
48
+ Vue .prototype .$myMethod = function (options ) {
49
+ // something logic ...
50
+ }
51
+ }
52
+ ```
53
+
54
+ ## 使用插件
55
+
56
+ 通过 Vue.use() 全局方法使用插件:
57
+
58
+ ``` js
59
+ // 调用 `MyPlugin.install(Vue)`
60
+ Vue .use (MyPlugin)
61
+ ```
62
+
63
+ 也可以传入一个选项对象:
64
+
65
+ ``` js
66
+ Vue .use (MyPlugin, { someOption: true })
67
+ ```
68
+
69
+ ` Vue.use ` 会自动阻止注册相同插件多次,届时只会注册一次该插件。
70
+
71
+ 一些插件,如 ` vue-router ` 如果 ` Vue ` 是全局变量则自动调用` Vue.use() ` 。不过在模块环境中应当始终显式调用 ` Vue.use() ` :
72
+
73
+ ``` js
74
+ // 通过 Browserify 或 Webpack 使用 CommonJS 兼容模块
75
+ var Vue = require (' vue' )
76
+ var VueRouter = require (' vue-router' )
77
+
78
+ // 不要忘了调用此方法
79
+ Vue .use (VueRouter)
80
+ ```
81
+
82
+ [ awesome-vue] ( https://github.com/vuejs/awesome-vue#libraries--plugins ) 集合了来自社区贡献的数以千计的插件和库。
83
+
84
+
85
+
You can’t perform that action at this time.
0 commit comments