解读element(一)message

组件用法

http://element-cn.eleme.io/#/zh-CN/component/message

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<div id="test" @click="open">
<!--内容填充,点击div调出message-->
</div>
</template>

<script>
export default {
methods: {
open() {
this.$message({//2.这里应该就是下面源代码mian.js里面的options
message: '恭喜你,这是一条成功消息',
type: 'success'
});
}
}
}
</script>

从用法上, 我们可以看出message组件在vue示例上添加了一个属性message, 所以可以在组件中通过 this.$message调用.

解读main.js源码

message/src/main.js

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
import Vue from 'vue';
import Main from './main.vue';
import { PopupManager } from 'element-ui/src/utils/popup';
import { isVNode } from 'element-ui/src/utils/vdom';
// 用Vue.extend构造器包含message组件的示例
let MessageConstructor = Vue.extend(Main);

let instance;
let instances = [];
let seed = 1; // 用于id计数

const Message = function(options) {
// 判断当前 Vue 实例是否运行于服务器。
if (Vue.prototype.$isServer) return;
options = options || {};
if (typeof options === 'string') {
options = {
message: options
};
}
let userOnClose = options.onClose;
let id = 'message_' + seed++;

// 自定义的关闭方法userOnClose
options.onClose = function() {
Message.close(id, userOnClose);
};
// 创建组件示例, 并传入参数
instance = new MessageConstructor({
data: options
});
instance.id = id;
if (isVNode(instance.message)) {
// slots 用于标记往哪个具名插槽中插入子组件内容。
instance.$slots.default = [instance.message];
instance.message = null;
}
// 挂载示例
instance.vm = instance.$mount();
// 添加到body底部
document.body.appendChild(instance.vm.$el);
instance.vm.visible = true;
instance.dom = instance.vm.$el;
// 层级设置
instance.dom.style.zIndex = PopupManager.nextZIndex();
// 添加到instances中
instances.push(instance);
return instance.vm;
};

['success', 'warning', 'info', 'error'].forEach(type => {
Message[type] = options => {
if (typeof options === 'string') {
options = {
message: options
};
}
options.type = type;
return Message(options);
};
});
// 关闭 传入id 和 回调函数, 从instances中移除
Message.close = function(id, userOnClose) {
for (let i = 0, len = instances.length; i < len; i++) {
if (id === instances[i].id) {
if (typeof userOnClose === 'function') {
userOnClose(instances[i]);
}
instances.splice(i, 1);
break;
}
}
};
// 关闭全部
Message.closeAll = function() {
for (let i = instances.length - 1; i >= 0; i--) {
// 遍历instances 调用close方法
instances[i].close();
}
};

export default Message;

Vue.extend(option)

使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
// 创建构造器 用于创建一个组件示例Profile
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount('#mount-point')