返回
定制化Vue3气泡对话框:实现文字换行、图标设置、箭头调整
前端
2023-11-10 21:59:45
我们先来介绍一下气泡对话框组件的核心代码:
<template>
<div class="chat-dialog">
<div class="dialog-wrapper">
<div class="dialog-content">
<p>{{ message }}</p>
</div>
<div class="dialog-icon" v-if="showIcon">
<img :src="iconSrc" alt="icon" />
</div>
<div class="dialog-arrow" :class="arrowDirection" v-if="showArrow"></div>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
props: {
message: {
type: String,
required: true
},
showIcon: {
type: Boolean,
default: false
},
iconSrc: {
type: String,
default: ''
},
showArrow: {
type: Boolean,
default: false
},
arrowDirection: {
type: String,
default: 'right'
}
},
setup() {
return {
messageRef: ref(null)
}
},
mounted() {
this.adjustArrowPosition()
},
methods: {
adjustArrowPosition() {
const messageWidth = this.messageRef.current.offsetWidth
const arrowWidth = this.$refs.dialogArrow.offsetWidth
const dialogWidth = this.$refs.dialogWrapper.offsetWidth
let arrowLeft = (dialogWidth - messageWidth - arrowWidth) / 2
if (this.arrowDirection === 'left') {
arrowLeft = -arrowWidth
}
this.$refs.dialogArrow.style.left = `${arrowLeft}px`
}
}
}
</script>
<style>
.chat-dialog {
position: relative;
width: 200px;
height: 100px;
padding: 10px;
background-color: #efefef;
border: 1px solid #ccc;
border-radius: 5px;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
}
.dialog-wrapper {
display: flex;
align-items: center;
}
.dialog-content {
flex: 1;
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
line-height: 1.5;
}
.dialog-icon {
width: 24px;
height: 24px;
margin-right: 10px;
}
.dialog-icon img {
width: 100%;
height: 100%;
object-fit: contain;
}
.dialog-arrow {
position: absolute;
width: 10px;
height: 10px;
background-color: #ccc;
transform: rotate(45deg);
}
.dialog-arrow.left {
left: -10px;
}
.dialog-arrow.right {
right: -10px;
}
</style>
这个组件提供了丰富的属性,包括message
(对话框内容)、showIcon
(是否显示图标)、iconSrc
(图标地址)、showArrow
(是否显示箭头)、arrowDirection
(箭头方向)。在组件内部,我们使用Vue3的响应式特性来动态控制这些属性,并在组件初始化时调整箭头的位置,确保箭头始终位于正确的位置。
接下来,让我们看看如何使用这个组件:
<template>
<div>
<ChatDialog message="你好,我是气泡对话框!" showIcon iconSrc="https://avatars.githubusercontent.com/u/3123951?v=4" showArrow arrowDirection="left" />
</div>
</template>
<script>
import ChatDialog from './ChatDialog.vue'
export default {
components: {
ChatDialog
}
}
</script>
在这个示例中,我们创建了一个名为App.vue
的文件,并在其中使用了ChatDialog
组件。我们在组件中设置了消息内容、图标地址、是否显示箭头以及箭头方向,这样就可以轻松地定制出我们想要的对话框样式。
最后,让我们运行这个应用程序,看看效果:
如你所见,我们成功地创建了一个功能强大的气泡对话框组件,它可以根据我们的需求进行定制,包括文字换行、图标设置、箭头调整等等。这个组件非常适合用于聊天应用程序、在线客服系统等需要气泡对话框的场景。