vue如何自定义封装API组件
更新时间:2022年03月31日 10:20:05 作者:吃柠檬的猫
这篇文章主要介绍了vue如何自定义封装API组件,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
自定义封装API组件
1.创建vue组件
<template>
<div >
<div class="alert">
<div class="alert-main" v-for="item in notices" :key="item.name">
<div class="alert-content">{{ item.content }}</div>
</div>
</div>
</div >
</template><script>
//多个提示框命名
let seed = 0;
function getUuid() {
return 'alert_' + (seed++);
}
export default {
data() {
return {
notices: []//多个提示框保存至数组
}
},
methods:{
add(notice) {
const name = getUuid();//获取当前提示框名称
//Object.assign 浅拷贝不会跳过那些值为 [null] 或 [undefined]的源对象
// Object.assign(target, ...sources);target: 目标对象,sources:源对象
let _notice = Object.assign({
name: name
}, notice);
//将当前提示框标签保存到notices
this.notices.push(_notice);
// 定时移除,单位:秒
const time= notice.time|| 1.5;
//1.5s后调用移除方法
setTimeout(() => {
this.remove(name);
}, time* 1000);
},
remove(name) {
const notices = this.notices;
for (let i = 0; i < notices.length; i++) {
if (notices[i].name === name) {
this.notices.splice(i, 1);
break;
}
}
}
}
}
</script><style lang="scss"> </style>
2.创建Alter.js生成组件
import Vue from 'vue'
import Alter from '/components/Alter/Alter.vue'
//Alter添加新属性,newInstance是个函数需求参数为properties
Alter.newInstance=properties=>{
const props=properties || {};
//创建一个Vue组件对象
const Instance=new Vue({
data:props,
render(h){
return h(Alter,{
props:props
})
}
});
//等待接口调用的时候在实例化组件,避免进入页面就直接挂载到body上
const component=Instance.$mount();
//实例化一个组件,然后挂载到body上
document.body.appendChild(component.$el);
//通过闭包维护alter组件的引用
const alter=Instance.$children[0];
return{
//Alter组件对外暴露的两个方法
add(noticeProps){
alter.add(noticeProps);
},
remove(name){
alter.remove(name);
}
}
}
//提示单例
let messageInstance;
function getMessageInstance(){
messageInstance=messageInstance || Alter.newInstance();
return messageInstance;
}
//定义函数实现
function notice({time='',content=''}){
let instance=getMessageInstance();
instance.add({
time:1.5,
content:''
})
}
//公布方法
export default{
info(options){
return notice(options);
}
}3.导入Vue
import alert from './alert.js'
// 挂载到Vue原型上
Vue.prototype.$Alert = alert
// 然后在组件中使用
this.$Alert.info({time: 1.5, content: '提示'})如何封装使用api形式调用的vue组件
在实际开发中一般有两种封装vue组件的方法:一种就是常用的的通过props父组件传值给子组件的方法:
子组件

父组件

还有一种就是通过调用api的形式,下面例子是本人在实际项目中封装的一个自定义图标的弹窗组件
首先实现组件的UI页面(css部分截图不完整)

在vue文件的同目录下新建alertTips.js文件

页面中调用方法:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
使用webpack打包后的vue项目如何正确运行(express)
这篇文章主要介绍了使用webpack打包后的vue项目如何正确运行(express) ,接下来通过本文给大家详细介绍,需要的朋友可以参考下2018-10-10
Vue 项目中如何使用fullcalendar 时间段选择插件(类似课程表格)
最近完成一个项目,需要选择一个会议室,但是最好能够通过在图上显示出该 会议室在某某时间段内已经被预定了,初看这个功能感觉很棘手,仔细分析下实现起来还是挺容易的,下面通过示例代码讲解Vue项目中使用fullcalendar时间段选择插件,感兴趣的朋友一起看看吧2024-07-07


最新评论