从模态弹框讲起
前端攻城?️对模态弹框一定很熟习,不管是套用bootstrap的照样本身写的,它常用来完成与用户的展现交互和处置惩罚一些数理逻辑。但是在用来展现小体量的信息时我以为它是过于巨大的,我们能够采纳更文雅的气泡卡片来展现那些小体量的信息。
就像如许的↓↓↓
先附上体验地点
完成
vue模版
<div class="v-popover-tag" @click.stop="pop($event)">
<slot></slot>
</div>
<div class="v-popover-wrap" :style="{left: x + 'px', top: y + 'px', visibility: show ? 'visible' : 'hidden'}" v-el:pop>
<div class="v-popover-box">
<div class="v-popover-title">{{title}}</div>
<div class="v-popover-content">{{content}}</div>
<div :class="['v-popover-arrow', placement == 'top' ? 'v-popover-arrow-top' : 'v-popover-arrow-bottom']" :style="{left: arrowLeft + 'px'}"></div>
</div>
</div>
这里对熟习vue的同砚来说没有什么特别的处所,主要有一个slot
标签会有疑问,在编译模版时碰到slot
标签会回到html
文档顶用响应的内容替代,运用体式格局能够参考官方文档vue-slot
数据
props: {
title: {
type: String,
default: '题目'
},
content: {
type: String,
default: '内容'
},
placement: {
type: String,
default: 'top'
}
},
data() {
return {
show: false,
arrowLeft: 0,
x: 0,
y: 0
}
}
来自父组件的数据title
和content
是必选项(虽然我也给它们设置了默许值),placement
代表气泡卡片的涌现位置,默许会涌如今触发目的的上方,临时支撑top和bottom。其他都是子组件的本身数据,用于掌握气泡卡片的显现隐蔽和位置。
事宜函数
pop(e) {
if(this.show){
this.show = false
return
}
var target = e.target
this.arrowLeft = target.offsetWidth / 2
this.x = target.offsetLeft
if(this.placement == 'top'){
this.y = target.offsetTop - this.$els['pop'].offsetHeight - 3
}else {
this.y = target.offsetTop + target.offsetHeight + 3
}
this.show = true
}
这里依托事宜的冒泡,slot
中的事宜会冒泡到子组件中定义的父层div
标签上,进而触发事宜实行后续的位置盘算。
scss
这方面难点主如果那两个小三角形的,其他的都比较简单。
.v-popover-arrow{
position: absolute;
width: 0;
height: 0;
border: 5px solid transparent;
margin-left: -5px;
&:after{
content: " ";
margin-left: -4px;
border: 4px solid transparent;
position: absolute;
width: 0;
height: 0;
}
}
.v-popover-arrow-top{
border-bottom-width: 0;
border-top-color: #d9d9d9;
bottom: -5px;
&:after{
border-top-color: #fff;
bottom: -3px;
}
}
运用
html:
<div id="app">
<v-popover :title="popTitle" :content="popContent" :placement="popPlacement">
<button class="btn btn-primary">点击弹出气泡卡片</button>
</v-popover>
</div>
js:
var btn = new Vue({
el: '#app',
data: {
popTitle: '我是题目'
popContent: '气泡内容气泡内容气泡内容气泡内容气泡内容气泡内容气泡内容气泡内容气泡内容',
popPlacement: 'top'
},
components: {
'v-popover': components.popover
}
})
这里我在组件标签中插了一个button
标签,上面提到的slot
终究就会被这个按钮替代,同时它的点击事宜会经由冒泡被触发。
打个广告
插播小广告。。。不要打我,我和@二胖手正在保护相干组件库web-style,待组件基础完善后,参考文档也会跟上,迎接关注,有什么好的发起也迎接议论。