需要实现的功能是:
固定顶部显示,有三种类型:成功,错误,警告。
显示消息提示时需要动画从上滑入。
这是message组件的代码:
<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 { 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 visible = ref(false)
setTimeout(() => {
visible.value = true
}, 5000)
return { style, visible }
}
}
</script>
<style scoped lang="less">
.down-enter-from {
transform: translate3d(0,-75px,0);
opacity: 0;
}
.down-enter-active {transition: all 0.5s;}
.down-enter-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>

vue3.0官网上写的是 v-enter-from, v开头,这个名字可以自己定义!!!
transtion的用法:(这是vue3.0官方上的用法)


1.给<Transition/> 绑定name名
2.css实现message组件从无到有的效果:

下面这个图就是对这个过程的 解析:

第二种方法实现: (Message-封装成函数调用):
message.vue: onMounted 组件创建完之后:

src/ components/ Message.js:
import { createVNode, render } from 'vue'
import XtxMessage from './xtx-message.vue'
// 2. 准备一个DOM容器
const div = document.createElement('div')
div.setAttribute('class', 'xtx-message-wrapper')
document.body.appendChild(div)
let time = null
export default ({ text, type }) => {
// 3. 创建虚拟dom (组件对象, props)
const vnode = createVNode(XtxMessage, { text, type })
// 4. 把虚拟dom渲染到div
render(vnode, div)
// 5. 设置定时器清空
clearTimeout(time)
time = setTimeout(() => {
render(null, div)
}, 1000)
console.log('message.js')
}
login.vue页面:
import Message from '@/components/Message.js'
const login = () => {
// Form 组件提供了一个 validate 函数作为整体表单校验,返回的是一个promise
target.value.validate().then((res) => {
console.log('表单校验结果', res)
if (res) {
Message({ type: 'success', text: '登陆成功' })
} else {
Message({ type: 'error', text: '校验失败' })
}
})
}
2136

被折叠的 条评论
为什么被折叠?



