天給大家分享的是Vue3系列之自定義桌面端對話框組件v3layer。
V3Layer 基于vue3.0構建的多功能PC網頁端彈窗組件。擁有超過10+種彈窗類型、30+種參數配置,支持拖拽(自定義拖拽區域)、縮放、最大化、全屏及自定義置頂層疊等功能。
在main.js中引入v3layer組件。
import { createApp } from 'vue'
import App from './App.vue'
// 引入Element-Plus組件庫
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
// 引入彈窗組件v3layer
import V3Layer from './components/v3layer'
createApp(App).use(ElementPlus).use(V3Layer).mount('#app')
v3layer支持組件式+函數式兩種調用方式。
<v3-layer
v-model="showDialog"
title="標題內容"
content="<div style='color:#f57b16;padding:30px;'>這里是內容信息!</div>"
z-index="2021"
lockScroll="false"
xclose
resize
dragOut
:btns="[
{text: '取消', click: ()=> showDialog=false},
{text: '確認', style: 'color:#f90;', click: handleSure},
]"
/>
<template v-slot:content>這里是自定義插槽內容信息!</template>
</v3-layer>
let $el=v3layer({
title: '標題內容',
content: '<div style='color:#f57b16;padding:30px;'>這里是內容信息!</div>',
shadeClose: false,
zIndex: 2021,
lockScroll: false,
xclose: true,
resize: true,
dragOut: true,
btns: [
{text: '取消', click: ()=> { $el.close() }},
{text: '確認', click: ()=> handleSure},
]
});
當彈窗類型為 message | notify | popover,調用方法如下:
v3layer.message({...})
v3layer.notify({...})
v3layer.popover({...})
vue3.0中提供了app.config.globalProperties 或 app.provide 兩種方式掛載全局函數。
// vue2中調用
methods: {
showDialog() {
this.$v3layer({...})
}
}
// vue3中調用
setup() {
// 獲取上下文
const { ctx }=getCurrentInstance()
ctx.$v3layer({...})
}
// vue2中調用
methods: {
showDialog() {
this.v3layer({...})
}
}
// vue3中調用
setup() {
const v3layer=inject('v3layer')
const showDialog=()=> {
v3layer({...})
}
return {
v3layer,
showDialog
}
}
v3layer支持如下30+參數靈活配置,實現各種彈窗場景。
|props參數|
v-model 是否顯示彈框
id 彈窗唯一標識
title 標題
content 內容(支持String、帶標簽內容、自定義插槽內容)***如果content內容比較復雜,推薦使用標簽式寫法
type 彈框類型(toast|footer|actionsheet|actionsheetPicker|android|ios|contextmenu|drawer|iframe)
layerStyle 自定義彈窗樣式
icon toast圖標(loading | success | fail)
shade 是否顯示遮罩層
shadeClose 是否點擊遮罩時關閉彈窗
lockScroll 是否彈窗出現時將body滾動鎖定
opacity 遮罩層透明度
xclose 是否顯示關閉圖標
xposition 關閉圖標位置(left | right | top | bottom)
xcolor 關閉圖標顏色
anim 彈窗動畫(scaleIn | fadeIn | footer | fadeInUp | fadeInDown | fadeInLeft | fadeInRight)
position 彈出位置(auto | ['100px','50px'] | t | r | b | l | lt | rt | lb | rb)
drawer 抽屜彈窗(top | right | bottom | left)
follow 跟隨元素定位彈窗(支持元素.kk #kk 或 [e.clientX, e.clientY])
time 彈窗自動關閉秒數(1、2、3)
zIndex 彈窗層疊(默認8080)
teleport 指定掛載節點(默認是掛載組件標簽位置,可通過teleport自定義掛載位置) teleport="body | #xxx | .xxx"
topmost 置頂當前窗口(默認false)
area 彈窗寬高(默認auto)設置寬度area: '300px' 設置高度area:['', '200px'] 設置寬高area:['350px', '150px']
maxWidth 彈窗最大寬度(只有當area:'auto'時,maxWidth的設定才有效)
maximize 是否顯示最大化按鈕(默認false)
fullscreen 全屏彈窗(默認false)
fixed 彈窗是否固定
drag 拖拽元素(可定義選擇器drag:'.xxx' | 禁止拖拽drag:false)
dragOut 是否允許拖拽到窗口外(默認false)
lockAxis 限制拖拽方向可選: v 垂直、h 水平,默認不限制
resize 是否允許拉伸尺寸(默認false)
btns 彈窗按鈕(參數:text|style|disabled|click)
++++++++++++++++++++++++++++++++++++++++++++++
|emit事件觸發|
success 層彈出后回調(@success="xxx")
end 層銷毀后回調(@end="xxx")
++++++++++++++++++++++++++++++++++++++++++++++
|event事件|
onSuccess 層打開回調事件
onEnd 層關閉回調事件
v3layer彈窗模板
<template>
<div ref="elRef" v-show="opened" class="vui__layer" :class="{'vui__layer-closed': closeCls}" :id="id">
<!-- //蒙版 -->
<div v-if="JSON.parse(shade)" class="vlayer__overlay" @click="shadeClicked" :style="{opacity}"></div>
<div class="vlayer__wrap" :class="['anim-'+anim, type&&'popui__'+type, tipArrow]" :style="[layerStyle]">
<div v-if="title" class="vlayer__wrap-tit" v-html="title"></div>
<div v-if="type=='toast'&&icon" class="vlayer__toast-icon" :class="['vlayer__toast-'+icon]" v-html="toastIcon[icon]"></div>
<div class="vlayer__wrap-cntbox">
<!-- 判斷插槽是否存在 -->
<template v-if="$slots.content">
<div class="vlayer__wrap-cnt"><slot name="content" /></div>
</template>
<template v-else>
<template v-if="content">
<iframe v-if="type=='iframe'" scrolling="auto" allowtransparency="true" frameborder="0" :src="content"></iframe>
<!-- message|notify|popover -->
<div v-else-if="type=='message' || type=='notify' || type=='popover'" class="vlayer__wrap-cnt">
<i v-if="icon" class="vlayer-msg__icon" :class="icon" v-html="messageIcon[icon]"></i>
<div class="vlayer-msg__group"><div v-if="title" class="vlayer-msg__title" v-html="title"></div><div v-html="content"></div></div>
</div>
<div v-else class="vlayer__wrap-cnt" v-html="content"></div>
</template>
</template>
<slot />
</div>
<div v-if="btns" class="vlayer__wrap-btns">
<span v-for="(btn,index) in btns" :key="index" class="btn" :style="btn.style" @click="btnClicked($event,index)" v-html="btn.text"></span>
</div>
<span v-if="xclose" class="vlayer__xclose" :class="!maximize&&xposition" :style="{'color': xcolor}" @click="close"></span>
<span v-if="maximize" class="vlayer__maximize" @click="maximizeClicked($event)"></span>
<span v-if="resize" class="vlayer__resize"></span>
</div>
<!-- 優化拖拽卡頓 -->
<div class="vlayer__dragfix"></div>
</div>
</template>
<script>
import { onMounted, onUnmounted, ref, reactive, watch, toRefs, nextTick } from 'vue'
import domUtils from './utils/dom.js'
// 索引,蒙層控制,定時器
let $index=0, $locknum=0, $timer={}, $closeTimer=null
export default {
props: {
// ...
},
emits: [
'update:modelValue'
],
setup(props, context) {
const elRef=ref(null);
const data=reactive({
opened: false,
closeCls: '',
toastIcon: {
// ...
},
messageIcon: {
// ...
},
vlayerOpts: {},
tipArrow: null,
})
onMounted(()=> {
if(props.modelValue) {
open();
}
window.addEventListener('resize', autopos, false);
})
onUnmounted(()=> {
window.removeEventListener('resize', autopos, false);
clearTimeout($closeTimer);
})
// 監聽彈層v-model
watch(()=> props.modelValue, (val)=> {
// console.log('V3Layer is now [%s]', val ? 'show' : 'hide')
if(val) {
open();
}else {
close();
}
})
// 打開彈窗
const open=()=> {
if(data.opened) return;
data.opened=true;
typeof props.onSuccess==='function' && props.onSuccess();
const dom=elRef.value;
// 彈層掛載位置
if(props.teleport) {
nextTick(()=> {
let teleportNode=document.querySelector(props.teleport);
teleportNode.appendChild(dom);
auto();
})
}
callback();
}
// 關閉彈窗
const close=()=> {
if(!data.opened) return;
let dom=elRef.value;
let vlayero=dom.querySelector('.vlayer__wrap');
let ocnt=dom.querySelector('.vlayer__wrap-cntbox');
let omax=dom.querySelector('.vlayer__maximize');
data.closeCls=true;
clearTimeout($closeTimer);
$closeTimer=setTimeout(()=> {
data.opened=false;
data.closeCls=false;
if(data.vlayerOpts.lockScroll) {
$locknum--;
if(!$locknum) {
document.body.style.paddingRight='';
document.body.classList.remove('vui__body-hidden');
}
}
if(props.time) {
$index--;
}
// 清除彈窗樣式
vlayero.style.width=vlayero.style.height=vlayero.style.top=vlayero.style.left='';
ocnt.style.height='';
omax && omax.classList.contains('maximized') && omax.classList.remove('maximized');
data.vlayerOpts.isBodyOverflow && (document.body.style.overflow='');
context.emit('update:modelValue', false);
typeof props.onEnd==='function' && props.onEnd();
}, 200)
}
// 彈窗位置
const auto=()=> {
// ...
autopos();
// 全屏彈窗
if(props.fullscreen) {
full();
}
// 彈窗拖動|縮放
move();
}
const autopos=()=> {
if(!data.opened) return;
let oL, oT
let pos=props.position;
let isFixed=JSON.parse(props.fixed);
let dom=elRef.value;
let vlayero=dom.querySelector('.vlayer__wrap');
if(!isFixed || props.follow) {
vlayero.style.position='absolute';
}
let area=[domUtils.client('width'), domUtils.client('height'), vlayero.offsetWidth, vlayero.offsetHeight]
oL=(area[0] - area[2]) / 2;
oT=(area[1] - area[3]) / 2;
if(props.follow) {
offset();
}else {
typeof pos==='object' ? (
oL=parseFloat(pos[0]) || 0, oT=parseFloat(pos[1]) || 0
) : (
pos=='t' ? oT=0 :
pos=='r' ? oL=area[0] - area[2] :
pos=='b' ? oT=area[1] - area[3] :
pos=='l' ? oL=0 :
pos=='lt' ? (oL=0, oT=0) :
pos=='rt' ? (oL=area[0] - area[2], oT=0) :
pos=='lb' ? (oL=0, oT=area[1] - area[3]) :
pos=='rb' ? (oL=area[0] - area[2], oT=area[1] - area[3]) :
null
)
vlayero.style.left=parseFloat(isFixed ? oL : domUtils.scroll('left') + oL) + 'px';
vlayero.style.top=parseFloat(isFixed ? oT : domUtils.scroll('top') + oT) + 'px';
}
}
// 元素跟隨定位
const offset=()=> {
let oW, oH, pS
let dom=elRef.value
let vlayero=dom.querySelector('.vlayer__wrap');
oW=vlayero.offsetWidth;
oH=vlayero.offsetHeight;
pS=domUtils.getFollowRect(props.follow, oW, oH);
data.tipArrow=pS[2];
vlayero.style.left=pS[0] + 'px';
vlayero.style.top=pS[1] + 'px';
}
// 最大化彈窗
const full=()=> {
// ...
}
// 恢復彈窗
const restore=()=> {
let dom=elRef.value;
let vlayero=dom.querySelector('.vlayer__wrap');
let otit=dom.querySelector('.vlayer__wrap-tit');
let ocnt=dom.querySelector('.vlayer__wrap-cntbox');
let obtn=dom.querySelector('.vlayer__wrap-btns');
let omax=dom.querySelector('.vlayer__maximize');
let t=otit ? otit.offsetHeight : 0
let b=obtn ? obtn.offsetHeight : 0
if(!data.vlayerOpts.lockScroll) {
data.vlayerOpts.isBodyOverflow=false;
document.body.style.overflow='';
}
props.maximize && omax.classList.remove('maximized')
vlayero.style.left=parseFloat(data.vlayerOpts.rect[0]) + 'px';
vlayero.style.top=parseFloat(data.vlayerOpts.rect[1]) + 'px';
vlayero.style.width=parseFloat(data.vlayerOpts.rect[2]) + 'px';
vlayero.style.height=parseFloat(data.vlayerOpts.rect[3]) + 'px';
}
// 拖動|縮放彈窗
const move=()=> {
// ...
}
// 事件處理
const callback=()=> {
// 倒計時關閉
if(props.time) {
$index++
// 防止重復點擊
if($timer[$index] !==null) clearTimeout($timer[$index])
$timer[$index]=setTimeout(()=> {
close();
}, parseInt(props.time) * 1000)
}
}
// 點擊最大化按鈕
const maximizeClicked=(e)=> {
let o=e.target
if(o.classList.contains('maximized')) {
// 恢復
restore();
} else {
// 最大化
full();
}
}
// 點擊遮罩層
const shadeClicked=()=> {
if(JSON.parse(props.shadeClose)) {
close();
}
}
// 按鈕事件
const btnClicked=(e, index)=> {
let btn=props.btns[index]
if(!btn.disabled) {
typeof btn.click==='function' && btn.click(e)
}
}
return {
...toRefs(data),
elRef,
close,
maximizeClicked,
shadeClicked,
btnClicked,
}
}
}
</script>
v3layer支持自定義拖拽區域 (drag:'#aaa'),拖動到窗口外 (dragOut:true)。支持iframe彈窗類型 (type:'iframe')。
配置 topmost:true 當前窗口會保持置頂。
ok,基于vue3.0開發pc端對話框組件就分享到這里。希望對大家有所幫助哈!
時瀏覽網站的時候經常會遇到點擊某些按鈕會彈出登錄提示或者注意事項提示的彈窗。那么這種彈窗是怎么實現的呢。實現方法有很多,不外乎就是點擊事件觸發相應的彈窗事件。
在這里介紹一個簡易實現的方法。
首先,這里的彈窗長這樣:
而原本頁面長這樣:
這里假定圖中深綠色的按鈕作為觸發彈窗事件的按鈕,在這里命名為btn1,然后就是彈窗的制作:
由圖可看出,彈窗是基于整個屏幕的,有個灰色背景遮罩,中間有一塊白色底帶有圖標文字說明的內容提示區,下面還有兩個按鈕,close是關閉彈窗的作用。了解了這些,就開始制作彈窗了:
1、html結構如下:
.tc{
width: 100%;
height: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 9;
background: rgba(0,0,0,.5);
display: none;
}
.tc .box{
width: 670px;
height: 404px;
background: #fff;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
box-sizing: border-box;
padding-top: 54px;
}
.tc .box .icon{
width: 110px;
height: 110px;
margin: auto;
}
.tc .box .t1{
font-size: 18px;
line-height: 28px;
color: #333;
text-align: center;
box-sizing: border-box;
padding: 0 70px;
margin-top: 38px;
}
.tc .box .t2{
display: flex;
justify-content: center;
margin-top: 48px;
}
.tc .box .t2 .btn1{
width: 195px;
height: 40px;
border: none;
background: #1296db;
color: #fff;
font-size: 18px;
display: block;
cursor: pointer;
}
.tc .box .t2 .btn2{
width: 128px;
height: 40px;
border: none;
background: #295965;
color: #fff;
font-size: 18px;
display: block;
margin-left: 16px;
cursor: pointer;
}
由于在整個彈窗的父級div里加了隱藏屬性:display:none; 所以在頁面上是看不到彈窗的,這個時候就要開始寫觸發彈窗的點擊事件了,上面假定的按鈕是btn1,彈窗這塊的父級div是 tc 。
<script>
$('.btn1').on('click',function(){
$('.tc').show();
})
</script>
這樣就寫好之后點擊 btn1 就能顯示彈窗了,現在彈窗出現的效果有了,那么點擊close關閉彈窗的效果也就不遠了
<script>
$('.tc .btn2').on('click',function(){
$('.tc').hide();
})
</script>
在這里把close 的類名命名為 btn2, 如上代碼就實現了點擊close按鈕關閉彈窗的功能。
將這兩個事件放在一起,節省一個script,也顯得美觀些就是這樣
<script>
$('.btn1').on('click',function(){
$('.tc').show();
})
$('.tc .btn2').on('click',function(){
$('.tc').hide();
})
</script>
到這里一個建議的點擊彈窗關閉的效果就實現了。
最近接到一個需求,需要在一些敏感操作進行前要求輸入賬號和密碼,然后將輸入的賬號和密碼加到接口請求的header里面。如果每個頁面都去手動導入彈窗組件,在點擊按鈕后彈出彈窗。再拿到彈窗返回的賬號密碼后去請求接口也太累了,那么有沒有更簡單的實現方式呢?
首先我們來看看什么是函數式彈窗?
函數式彈窗是一種使用函數來創建彈窗的技術。它可以簡化彈窗的使用,只需要在需要彈窗的地方調用函數就可以了。那么這里使用函數式彈窗就能完美的解決我們的問題。
我們只需要封裝一個showPasswordDialog函數,調用該函數后會彈出一個彈窗。該函數會返回一個resolve后的值就是賬號密碼的Promise。然后在http請求攔截器中加一個needValidatePassword字段,攔截請求時如果該字段為true,就await調用showPasswordDialog函數。拿到賬號和密碼后塞到請求的header里面。這樣就我們就只需要在發起請求的地方加一個needValidatePassword: true配置就行了。
這個是簡化后template中的代碼,和Element Plus官網中的demo代碼差不多,沒有什么說的。
<template>
<el-dialog :model-value="visible" title="賬號和密碼" @close="handleClose">
<!-- 省略賬號、密碼表單部分... -->
<el-button type="primary" @click="submitForm()">提交</el-button>
</el-dialog>
</template>
這個是簡化后的script代碼,大部分和Element Plus官網的demo代碼差不多。需要注意的是我們這里將close關閉事件和confirm確認事件定義在了props中,而不是在emits中,因為后面函數式組件會通過props將這兩個回調傳入進來。具體的我們下面會講。
<script setup lang="ts">
interface Props {
visible: boolean;
close?: ()=> void;
confirm?: (data)=> void;
}
const props=defineProps<Props>();
const emit=defineEmits(["update:visible"]);
const submitForm=async ()=> {
// 省略validate表單校驗的代碼
// 這里的data為表單中輸入的賬號密碼
props.confirm?.(data);
handleClose();
};
const handleClose=()=> {
emit("update:visible", false);
props.close?.();
};
</script>
createApp函數會創建和返回一個vue的應用實例,也就是我們平時常說的app,該函數接受兩個參數。第一個參數為接收一個組件,也就是我們平時寫的vue文件。第二個參數為可選的對象,這個對象會傳遞給第一個參數組件的props。
舉個例子:
import MyComponent from "./MyComponent"
const app=createApp(MyComponent, {
visible: true
})
在這個例子中我們基于MyComponent組件生成了一個app應用實例,如果MyComponent組件的props中有定義visible,那么visible就會被賦值為true。
調用createApp函數創建的這個應用實例app實際就是在內存中創建的一個對象,并沒有渲染到瀏覽器的dom上面。這個時候我們就要調用應用實例app暴露出來的mount方法將這個組件掛載到真實的dom上面去。mount方法接收一個“容器”參數,用于將組件掛載上去,可以是一個實際的 DOM 元素或是一個 CSS 選擇器字符串。比如下面這個例子是將組件掛載到body上面:
app.mount(document.body)
app提供了很多方法和屬性,詳見 vue官網。
我們希望showPasswordDialog函數返回一個Promise,resolve的值就是彈窗中輸入的表單。例如,我們可以使用以下代碼使用showPasswordDialog函數:
try {
// 調用這個就會彈出彈窗
const res: RuleForm=await showPasswordDialog();
// 這個res就是輸入的賬號密碼
console.log("res", res);
} catch (error) {
console.log(error);
}
經過上面的介紹我們知道了可以調用createApp函數傳入指定組件生成app,然后使用app.mount方法將這個組件掛載到指定的dom上面去。那么現在思路就清晰了,我們只需要將我們前面實現的彈窗組件作為第一個參數傳遞給createApp函數。第二個參數傳入一個對象給彈窗組件的props,用以控制打開彈窗和注冊彈窗關閉和確認的事件回調。下面是實現的showPasswordDialog函數
import { App, createApp } from "vue";
import PasswordDialog from "./index.vue";
// 這個index.vue就是我們前面實現的彈窗組件
export async function showPasswordDialog(): Promise<RuleForm> {
return new Promise((resolve, reject)=> {
let mountNode=document.createElement("div");
let dialogApp: App<Element> | undefined=createApp(PasswordDialog, {
visible: true,
close: ()=> {
if (dialogApp) {
dialogApp.unmount();
document.body.removeChild(mountNode);
dialogApp=undefined;
reject("close");
}
},
confirm: (res: RuleForm)=> {
resolve(res);
dialogApp?.unmount();
document.body.removeChild(mountNode);
dialogApp=undefined;
},
});
document.body.appendChild(mountNode);
dialogApp.mount(mountNode);
});
}
在這個showPasswordDialog函數中我們先創建了一個div元素,再將彈窗組件傳遞給了createApp函數生成一個dialogApp的實例。然后將創建的div元素掛載到body上面,再調用mount方法將我們的彈窗組件掛載到創建的div元素上,至此我們實現了通過函數式調用將彈窗組件渲染到body中。
現在我們再來看看傳入到createApp函數的第二個對象參數,我們給這個對象分別傳入了visible屬性、close和confirm回調方法,分別會賦值給彈窗組件props中的visible、close、confirm。
彈窗組件中觸發關閉事件時會調用props.close?.(),實際這里就是在調用我們傳入的close回調方法。在這個方法中我們調用了實例的unmount方法卸載組件,然后將創建的彈窗組件dom從body中移除,并且返回一個reject的Promise。
當我們將賬號和密碼輸入完成后,會調用props.confirm?.(ruleForm),這里的ruleForm就是我們表單中的賬號和密碼。實際這里就是在調用我們傳入的confirm回調方法,接下來同樣也是卸載組件和移除彈窗組件生成的dom,并且返回一個resolve值為賬號密碼表單的Promise。
這篇文章主要介紹了如何創建函數式彈窗:
作者:歐陽碼農
鏈接:https://juejin.cn/post/7322229620391673908
*請認真填寫需求信息,我們會在24小時內與您取得聯系。