用Vue.extend构建消息提示组件的方法实例

网友投稿 242 2023-04-22


用Vue.extend构建消息提示组件的方法实例

前提

前段时间自己做的vue练手项目,需要一个通用的消息提示组件,但是消息提示这种组件我更想用方法来调用,而不是在各个页面上都添加个组件(那样感觉很麻烦,重度懒癌患者),于是就上网差查了查,并研究了EPOFbpRfolementUI的message源码。自己弄出来一个简陋的消息提示组件

Vue.extend是什么

按照官方文档说法,他是一个类构造器,用来创建一个子类vue并返回构造POFbpRfo函数,而Vue.component它的任务是将给定的构造函数与字符串ID相关联,以便Vue.js可以在模板中接收它。

了解了这点之后我们开始做我们的消息提示组件吧。

消息提示组件

首先我们先创建我们的提示组件的模板

&POFbpRfolt;/span>

{{message}}

之后我们需要用将message.vue传到Vue.extend()里

import Vue from 'vue';

let MessageBox = Vue.extend(require('./message.vue'));

let instance;

var message = function(options){

if(typeof options === 'string'){

options = {

message: options

}

}

//生成组件

instance = new MessageBox({

data: options

})

//组件需要挂载在dom元素上

instance.vm = instance.$mount();

//根据不同的类型,设置不同消息的背景颜色

if(options.type){

instance.vm.$el.children[0].className += ` icon__${options.type}`;

}

document.body.appendChild(instance.vm.$el);

return instance.vm;

}

const type = ['success', 'info', 'warning', 'error'];

type.forEach((type)=>{

message[type] = options =>{

if(typeof options === 'string'){

options = {

message: options

}

}

options.type = type;

return message(options);

}

})

export default message;

之后用挂在全局方法上,之后用this.$message()方法调用

vue.prototype.$message = message;

最后的效果图


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:spring集成mybatis实现mysql数据库读写分离
下一篇:Vue项目中quill
相关文章

 发表评论

暂时没有评论,来抢沙发吧~