vue3写一个toast组件
时间: 2023-02-07 16:33:04 浏览: 120
好的,那我就来给你介绍一下如何在 Vue 3 中写一个 Toast 组件。
首先,你需要新建一个 Vue 3 组件,你可以使用 Vue 3 的 Composition API 来实现。
```
import { ref, reactive, computed } from 'vue'
export default function useToast() {
// 使用 ref 来声明一个可变的变量
const message = ref('')
// 使用 reactive 来声明一个反应性的对象
const toast = reactive({
show: false,
type: 'success',
})
// 使用 computed 来声明一个计算属性
const className = computed(() => `toast toast-${toast.type}`)
// 定义一个方法来显示 Toast
function show(type, msg) {
toast.type = type
message.value = msg
toast.show = true
}
// 定义一个方法来隐藏 Toast
function hide() {
toast.show = false
}
return {
message,
toast,
className,
show,
hide,
}
}
```
然后你就可以在组件的 template 中使用这些变量和方法来实现你的 Toast 组件了。
```
<template>
<transition name="fade">
<div v-if="toast.show" :class="className">{{ message }}</div>
</transition>
</template>
<script>
import useToast from './useToast'
export default {
setup() {
return useToast()
},
}
</script>
<style>
.toast {
padding: 10px;
border-radius: 4px;
}
.toast-success {
background-color: green;
color: white;
}
.toast-error {
background-color: red;
color: white;
}
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
```
在其他组件中使用 Toast 组件的方法也很简单,只需要在其他组件中引入 Toast