# 文档初探(十一): Mixin
# 什么是 Mixin, 为什么需要 Mixin
我们在写了许多个 Vue 组件时可能会发现, 这些组件的一些选项(属性, options)是一样的, 那么自然就会想把这些相同的选项抽离出来成为一个共用的选项. 这就是 Mixin.
# 基本用法
const mixIns = { created() { console.log("mixin is awesome"); }, data() { return { protoData: 1 }; }, methods: { add() { this.protoData += 1; } } }; Vue.component("foo", { template: ` <div> foo <p>{{protoData}}</p> <button @click="add">foo +1</button> </div> `, mixins: [mixIns] }); Vue.component("bar", { template: ` <div> foo <h1>{{protoData}}</h1> <button @click="add">bar +1</button> </div> `, mixins: [mixIns] }); new Vue({ el: "#app", template: ` <div> <foo /> <bar /> </div> ` });
Copied!
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
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
# 选项合并
如果 mixin 与组件data
属性冲突了, 那么会优先选择组件的data
属性, 没有冲突的则会合并. 而钩子函数发生冲突时, mixin 的钩子会先执行, 然后执行组件的钩子函数.如果与组件的对象属性(methods
, components
, directives
)发生冲突, 然后优先选择组件的对象属性, 没有冲突的则会合并.
# 全局 Mixins
我们也可以全局地声明 mixin, 那么所有的组件都会直接引用这个 mixin:
Vue.mixin({ created() { console.log("mixin is awesome"); }, data() { return { protoData: 1 }; }, methods: { add() { this.protoData += 1; } } }); Vue.component('mix', { // customized options // global mixin also inject here }) new Vue({ // ...options // global mixin will be inject here automatically })
Copied!
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25