Vue基本组件/插件开发

一、组件和插件的区别
  1. vue插件可以将自己的模块添加到Vue原型对象上,然后组件中可以通过this直接引用。还要就是通过插件机制,可以通过一个入口,就可以将一系列组件添加到环境中,直接使用
  2. 插件是采用通用接口编写的,多用于制作好的东西功能扩展。
  3. vue组件只是一个独立的模块,可重复使用并且可以和其他对象进行交互的对象
  4. 插件通常会为 Vue 添加全局功能。插件的范围没有限制——一般有下面几种:
    添加全局方法或者属性,如: vue-custom-element
    添加全局资源:指令/过滤器/过渡等,如 vue-touch
    通过全局 mixin 方法添加一些组件选项,如: vue-router
    添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
    一个库,提供自己的 API,同时提供上面提到的一个或多个功能,如 vue-router
    Vue.js 的插件应当有一个公开方法 install 。
  5. 如果你的模块或者组件想对外公开,最友好的方式就是通过插件机制提供
二、简单构建一个全局组件Message(消息提示)
1.组件模板
/* components/Message/index.vue */
< template >
< div class= "ta-message" v-if=" isShow" >
< span >{{ message}} </ span >
</ div >
</ template >
< script >
export default {
name: 'Message',
data () {
return {
}
},
props:{
message: {
type: String,
default: '成功'
},
isShow: {
type: Boolean,
default: true
}
},
methods:{
close(){
this. isShow = false;
}
}
}
</ script >


2.给组件添加全局功能(插件)
/* components/Message/index.js */
import msg from './index.vue';

//定义插件对象
const Message = {};
//Vue的install方法,用于定义vue插件
Message. install = function( Vue, options){
const MessageInstance = Vue. extend( msg);
let currentMsg;
const initInstance = () =>{
//实例化vue示例
currentMsg = new MessageInstance();
let msgEl = currentMsg. $mount(). $el;
document. body. appendChild( msgEl);
};
//在Vue的原型上添加实例,以全局调用
Vue. prototype. $msg = {
showMsg( options){
if(! currentMsg){
initInstance();
}
Object. assign( currentMsg, options); //将页面的对象传给currentMsg对象,否则阿会使用原有的
setTimeout(() => {
currentMsg. close();
}, 1000);
}
}
};
export default Message;

3.全局使用
// main.js
import Message from './components/Message/index'
Vue. use( Message);

4.页面调用
showconfirm(){
this. $msg. showMsg({
isShow: true
});
}







猜你喜欢

转载自blog.csdn.net/qq_32439381/article/details/79536322
今日推荐