效果:
组件功能分析:
-
固定顶部显示,有三种类型:成功,错误,警告。
-
显示消息提示时需要动画从上滑入且淡出。
-
组件使用的方式不够便利,封装成工具函数方式。
注:Vue2.0使用的是Vue.prototype.$message = function(){}
Vue3.0中使用的是app.config.globalProperties = function(){}挂载原型方法
使用组件:
<Message text="手机号或密码错误" type="error" />
全局消息提示组件message.vue
<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 { ref, onMounted } 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)
// 组件渲染成功后触发,默认是false不显示,用了生命周期dom节点有了之后,再次将isShow转化为了true
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 0.5s;
}
&-to {
transform: none;
opacity: 1;
}
}
}
</style>
定义了message.js文件
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)
export default function({ text, type }) {
let timer = null
// createVNode用于创建虚拟的组件
// 参数一支持组件
// 参数二表示传递给组件的选项
const vnode = createVNode(XtxMessage, { text, type })
// console.log('hello')
// render函数 参数一表示需要渲染的内容(虚拟节点)
// 参数二:标书要渲染的目标位置
render(vnode, div)
clearTimeout(timer)
timer = setTimeout(() => {
render(null, div)
}, 3000)
}
// Message({text:"登录失败", type:"warn"})
main.js中导入注册
import Message from './Message.js'
// 扩展一个实例方法
app.config.globalProperties.$message = Message
如何使用?两种方式
const handlerLogin = async () => {
const valid = await target.value.validate()
console.log(valid)
if (valid) {
// 调用接口实现登录
// 第一种方法:Message({ text: '登录成功呀', type: 'success' })
instance.proxy.$message({ text: '登录成功呀', type: 'success' })
} else {
}
}
// 使用instance.proxy相当于this
// 使用Message({ text: '登录成功呀', type: 'success' })的时候,要导入Message.js文件路径