https://blog.csdn.net/m0_49159526/article/details/120774801
https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html
vue.prototype
可能会在很多组件里用到数据/实用工具,但是不想污染全局作用域。这种情况下,你可以通过在原型上定义它们使其在每个 Vue 的实例中可用。
Vue.prototype.$appName = ‘My App’
1.用 Vue.extend 创建组件的模板(构造函数)
2.创建一个函数,在函数内部, 实例化组件并进行挂载到相应元素上
3.将创建的这个函数绑定到Vue原型上,就可以通过this .访问了
element 源码
https://github.com/zhouxiaoying/element/blob/dev/packages/message/src/main.js
import Vue from "vue";
import message from "./main.vue";
// 1.用 Vue.extend 创建组件的模板(构造函数)
let messageConstructor = Vue.extend(message);
let instance;
const Message = function(options) {// options是传入的参数配置 {message: '成功',type: "success"offset: 80}
// 2.实例化组件
instance = new messageConstructor({ data: options }); // 把options导入data中
// 3.组件挂载
instance.$mount();
document.body.appendChild(instance.$el);
// 设置offset
let verticalOffset = options.offset || 20;
instance.verticalOffset = verticalOffset;
instance.duration = options.duration || 3000;
return instance;
};
export default Message;
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';
import { isObject } from 'element-ui/src/utils/types';
let MessageConstructor = Vue.extend(Main);
let instance;
let instances = [];
let seed = 1;
const Message = function(options) {
if (Vue.prototype.$isServer) return;
options = options || {};
if (typeof options === 'string') {
options = {
message: options
};
}
let userOnClose = options.onClose;
let id = 'message_' + seed++;
options.onClose = function() {
Message.close(id, userOnClose);
};
instance = new MessageConstructor({
data: options
});
instance.id = id;
if (isVNode(instance.message)) {
instance.$slots.default = [instance.message];
instance.message = null;
}
instance.$mount();
document.body.appendChild(instance.$el);
let verticalOffset = options.offset || 20;
instances.forEach(item => {
verticalOffset += item.$el.offsetHeight + 16;
});
instance.verticalOffset = verticalOffset;
instance.visible = true;
instance.$el.style.zIndex = PopupManager.nextZIndex();
instances.push(instance);
return instance;
};
https://github.com/zhouxiaoying/element/blob/dev/src/index.js
Vue.prototype.
l
o
a
d
i
n
g
=
L
o
a
d
i
n
g
.
s
e
r
v
i
c
e
;
V
u
e
.
p
r
o
t
o
t
y
p
e
.
loading = Loading.service; Vue.prototype.
loading=Loading.service;Vue.prototype.msgbox = MessageBox;
Vue.prototype.
a
l
e
r
t
=
M
e
s
s
a
g
e
B
o
x
.
a
l
e
r
t
;
V
u
e
.
p
r
o
t
o
t
y
p
e
.
alert = MessageBox.alert; Vue.prototype.
alert=MessageBox.alert;Vue.prototype.confirm = MessageBox.confirm;
Vue.prototype.
p
r
o
m
p
t
=
M
e
s
s
a
g
e
B
o
x
.
p
r
o
m
p
t
;
V
u
e
.
p
r
o
t
o
t
y
p
e
.
prompt = MessageBox.prompt; Vue.prototype.
prompt=MessageBox.prompt;Vue.prototype.notify = Notification;
Vue.prototype.$message = Message;