目的:在接口请求报错的时候给用户进行提示
组件功能分析:
- 固定顶部显示,有三种类型:成功,错误,警告。
- 显示消息提示时需要动画从上滑入且淡出。
- 组件使用的方式不够便利,封装成工具函数方式。
大致实现步骤:
-
先把布局,和三种情况的显示,完成。
- 定义组件:
src/components/xtx-message.vue
- 定义组件:
<template>
<Transition name="down">
<div class="xtx-message" :style="style[type]" v-show="visible">
<!-- 上面绑定的是样式 -->
<!-- 不同提示图标会变 -->
<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'
}
</script>
<script setup>
defineProps({
text: {
type: String,
default: ''
},
type: {
type: String,
// warn 警告 error 错误 success 成功
default: 'warn'
}
})
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 visible = ref(false)
onMounted(() => {
visible.value = true
})
</script>
<style scoped lang="less">
.down {
&-enter {
&-from {
transform: translate3d(0, -75px, 0);
opacity: 0;
}
&-active {
transition: all 0.5s;
}
&-to {
transform: none;
opacity: 1;
}
}
}
.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;
}
}
</style>
- 封装成vue实例函数式调用
- vue3.0使用app.config.globalProperties挂载原型方法
- 也支持直接导入函数使用
src/components/Message.js
// 提供一个能够显示xtx-message组件的函数
// 这个函数将来:导入直接使用,也可以挂载在vue实例原型上
// import Message from 'Message.js' 使用 Message({type:'error',text:'提示文字'})
// this.$message({type:'error',text:'提示文字'})
import XtxMessage from './xtx-message'
import { createVNode, render } from 'vue'
// dom容器
const div = document.createElement('div')
div.setAttribute('class', 'xtx-message-container')
document.body.appendChild(div)
// 定时器标识
let timer = null
export default ({ type, text }) => {
// 渲染组件
// 1. 导入消息提示组件
// 2. 将消息提示组件编译为虚拟节点(dom节点)
// createVNode(组件,属性对象(props))
const vnode = createVNode(XtxMessage, { type, text })
// 3. 准备一个装载消息提示组件的DOM容器
// 4. 将虚拟节点渲染在容器中
// render(虚拟节点,DOM容器)
render(vnode, div)
// 5. 3s后销毁组件
clearTimeout(timer)
timer = setTimeout(() => {
render(null, div)
}, 3000)
}
- 在登录逻辑中使用
src/views/login/index.vue
import Message from '@/components/Message'
// 帐号密码登录
userAccountLogin(form).then(data => {
// 成功
}).catch(e => {
// 失败
Message({ type: 'error', text: '登录失败' })
})