1、定义一个Message.vue组件其内容如下
<template>
<Transition name="down">
<div class="xtx-message" :style="style[type]" v-show="visible">
<span class="text">{{text}}</span>
</div>
</Transition>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'Message',
props: {
type: {
type: String,
default: 'warn'
},
text: {
type: String,
default: ''
}
},
setup () {
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(true)
return { style, visible }
}
}
</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>
2、创建一个叫Message.js的文件其内容如下:
import { createVNode, render } from 'vue'
import HelloWorld from "@/components/Message.vue";
const div = document.createElement('div')
div.setAttribute('class', 'xtx-msssage-container')
document.body.appendChild(div)
let timer = null
export default ({ type, text }) => {
const vnode = createVNode(HelloWorld, { type, text })
render(vnode, div)
clearTimeout(timer)
timer = setTimeout(() => {
render(null, div)
}, 3000)
}
3、在app.vue中导入并使用:
<template>
<div class="btn" @click="btn">点击弹出消息提示框</div>
</template>
<script setup>
import Message from "@/Message";
import {onMounted} from "vue";
const btn = ()=>{
Message({type:'warn', text:"hello world"})
}
</script>
<style lang="less" scoped>
.btn{
width: 300px;
height: 40px;
text-align: center;
line-height: 40px;
background-color: deeppink;
}
</style>
4、效果如下:当点击左边按钮后会弹出一个消息提示框,3秒后关闭
5、如果想使用this.$message这种方式则需定义一个UI.js文件用来挂载Message.js其内容如下:
import Message from "@/Message";
export default {
install (app) {
app.config.globalProperties.$message = Message
}
}
6、在main.js中导入并使用use挂载到app上,如下所示
import { createApp } from 'vue'
import App from './App.vue'
import UI from "@/UI";
createApp(App).use(UI).mount('#app')
这种方式的缺点是还是得在选项式上才方便使用,在组合式方式上不推荐