1.先定义一个消息提示组件
<template>
<transition name="down">
<div class="xtx-message" :style="style[type]" v-show="isShow">
<!-- 上面绑定的是样式 -->
<!-- 不同提示图标会变 -->
<i class="iconfont" :class="[style[type].icon]"></i>
<span class="text">{{ text }}</span>
</div>
</transition>
</template>
<script>
import { onMounted, ref } from 'vue'
export default {
name: 'XtxMessage',
props: {
text: {
type: String,
default: ''
},
type: {
type: String,
// warn 警告 error 错误 success 成功
default: 'warn'
}
},
setup () {
// 定义一个对象,包含三种情况的样式,对象key就是类型字符串
const style = {
warn: {
icon: 'icon-warning',
color: '#E6A23C',
backgroundColor: 'rgb(253, 246, 236)',
borderColor: 'rgb(250, 236, 216)'
},
error: {
icon: 'icon-shanchu',
color: '#F56C6C',
backgroundColor: 'rgb(254, 240, 240)',
borderColor: 'rgb(253, 226, 226)'
},
success: {
icon: 'icon-queren2',
color: '#67C23A',
backgroundColor: 'rgb(240, 249, 235)',
borderColor: 'rgb(225, 243, 216)'
}
}
// 定义一个数据控制显示隐藏,默认是隐藏,组件挂载完毕显示
const isShow = ref(false)
onMounted(() => {
isShow.value = true
})
return { style, isShow }
}
}
</script>
<style scoped lang="less">
.xtx-message {
width: 300px;
height: 50px;
position: fixed;
z-index: 9999;
left: 50%;
margin-left: -150px;
top: 25px;
line-height: 50px;
padding: 0 25px;
border: 1px solid #e4e4e4;
background: #f5f5f5;
color: #999;
border-radius: 4px;
i {
margin-right: 4px;
vertical-align: middle;
}
.text {
vertical-align: middle;
}
}
.down {
&-enter{
&-from{
transform: translate3d(0,-75px,0);
opacity: 0;
}
&-active{
transition: all .5s;
}
&-to{
opacity: 1;
transform: none;
}
}
}
</style>
2.创建一个函数调用组件逻辑文件(components/library/message.js)
// 实现使用函数调用xtx-message组件的逻辑
import { createVNode, render } from 'vue'
import XtxMessage from './xtx-message.vue'
// 准备dom容器
const div = document.createElement('div')
div.setAttribute('class', 'xtx-message-container')
document.body.appendChild(div)
// 定时器标识
let timer = null
export default ({ type, text }) => {
// 实现:根据xtx-message.vue渲染消息提示
// 1. 导入组件
// 2. 根据组件创建虚拟节点
// createVNode(组件,属性对象props)
const vnode = createVNode(XtxMessage, { type, text })
// 3. 准备一个DOM容器
// 4. 把虚拟节点渲染DOM容器中
// render(虚拟DOM节点,真实DOM容器)
render(vnode, div)
// 5. 开启定时,移出DOM容器内容
clearTimeout(timer)
timer = setTimeout(() => {
render(null, div)
}, 3000)
}
3.在到vue插件中注册使用 (components/library/index.js)
import Message from './Message'
export default {
install (app) {
// 在app上进行扩展,app提供 component directive 函数
// 如果要挂载原型 app.config.globalProperties 方式
app.component(Message, Message)
}
}
4.到vue文件出口main中导入挂载
import ui from './components/library'
createApp(App).use(ui).mount('#app')
5.在组件内部直接引入并且使用
import message from '@/components/library/Message'
message({ type: 'error', text: '用户名或密码不正确' })