很多时候,在开发项目的时候是需要抽离公共组件和业务组件的。而有些公共组件在全局注册的同时可能还需要拓展成vue的实例方法,通过把它们添加到 Vue.prototype 上实现,方便直接使用js全局调用。拿一个Message组件做例子吧,代码比较简单,就直接上代码了。
- 首先开发好Message.vue文件。
<template>
<div class='y-mask-white-dialog' v-show='show'>
<div class='y-message animated zoomIn' >
<span v-html="msg"></span>
</div>
</div>
</template>
<script>
export default {
name: 'yMessage',
props: {
msg: String,
timeout: Number,
callback: Function,
icon: String,
},
data() {
return {
show: true,
};
}
};
</script>
<style lang="stylus" scoped>
.y-mask-white-dialog {
background-color: rgba(0, 0, 0, .4);
position: fixed;
z-index: 999;
bottom: 0;
right: 0;
left: 0;
top: 0;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.y-message {
min-width: 2.9rem;
max-width: 5.5rem;
width:100%;
padding: 0.32rem;
font-size: 14px;
text-align: center;
border-radius: 4px;
background :rgba(0,0,0,0.8);
color: #fff;
animation: zoomIn .15s ease forwards;
}
</style>
- 构建Message的Constructor
import Vue from 'vue';
const MsgConstructor = Vue.extend(require('./Message.vue'));
const instance = new MsgConstructor({
// el: document.createElement('div'),
}).$mount(document.createElement('div'));
MsgConstructor.prototype.closeMsg = function () {
const el = instance.$el;
el.parentNode && el.parentNode.removeChild(el);
typeof this.callback === 'function' && this.callback();
};
const Message = (options = {}) => {
instance.msg = options.msg;
instance.timeout = options.timeout || 2000;
instance.icon = options.icon;
instance.callback = options.callback;
document.body.appendChild(instance.$el);
const timer = setTimeout(() => {
clearTimeout(timer);
instance.closeMsg();
}, instance.timeout + 100);
};
export default Message;
- 在main.js里面进行组件注册
import Message from './components/Message';
Vue.component(Message.name, Message)
Vue.prototype.$message = Message
然后你就可以尽情使用Message组件了
this.$message({
msg: 'test message'
// ...
})