创建和使用 Toast 组件
使用 fixed 定位, 弹出 1.5 秒后自动隐藏,并添加淡入淡出过渡效果
<template>
<transition name="fade">
<div class="toast" v-if="showToast">{{message}}</div>
</transition>
</template>
<script lang="ts">
export default {
props: ['message', 'showToast']
}
</script>
<style lang="scss" scoped>
.toast {
padding: 16px;
border-radius: 5px;
background: rgba(0, 0, 0, 0.35);
color: white;
font-size: 16px;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 5;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 750ms ease;
}
</style>
使用
<template>
// ...
<Toast :showToast="data.showToast" :message="data.message"/>
</template>
<script>
import Toast from '@/components/Toast.vue'
export default {
components: {
Toast
},
setup(){
const data = reactive(
{
message: '',
showToast: false
}
)
const showToast = (message: string) => {
data.showToast = true
data.message = message
setTimeout(() => {
data.showToast = false
data.message = ''
}, 1500)
}
const handleLogin = async () => {
try {
// ...
if(result.data.verifySuccess === true) {
// ...
} else {
showToast('用户名或密码错误')
}
} catch(e) {
showToast('请求失败')
}
}
return {
data,
handleLogin,
}
}
}
</script>
封装逻辑代码
目前Toast组件的逻辑代码分散在其他组件中,应整合到一起,以便重复使用
封装成 useToastEffect 放在 Toast 组件中并 export
<template>
<transition name="fade">
<div class="toast" v-if="showToast">{{message}}</div>
</transition>
</template>
<script lang="ts">
import { reactive } from "vue"
export default {
props: ['message', 'showToast']
}
export const useToastEffect = () => {
const toastData = reactive(
{
message: '',
showToast: false
}
)
const showToast = (message: string) => {
toastData.showToast = true
toastData.message = message
setTimeout(() => {
toastData.showToast = false
toastData.message = ''
}, 2000)
}
return {
toastData,
showToast
}
}
</script>
其他组件要使用直接 import 即可, 很像 react 的hooks
<template>
<div class="login">
// ...
<Toast :showToast="toastData.showToast" :message="toastData.message"/>
</div>
</template>
<script lang="ts">
import Toast, {useToastEffect} from '@/components/Toast.vue'
export default {
components: {
Toast
},
setup(){
// ...
const {toastData, showToast} = useToastEffect()
const handleLogin = async () => {
try {
// ...
if(result.data.verifySuccess === true) {
// ...
} else {
showToast('用户名或密码错误')
}
} catch(e) {
showToast('请求失败')
}
}
return {
data,
handleLogin,
toastData
}
}
}
</script>