vue 显示 自定义toast,支持设置消失时间
时间: 2023-08-16 19:05:56 浏览: 58
你可以通过以下步骤来实现自定义 Toast 并支持设置消失时间:
1. 在 Vue 项目中创建一个自定义的 Toast 组件,可以参考下面的代码:
```vue
<template>
<div class="toast" v-show="show" :class="type">
{{ message }}
</div>
</template>
<script>
export default {
name: 'Toast',
props: {
message: String,
type: {
type: String,
default: 'info',
},
time: {
type: Number,
default: 3000,
},
},
data() {
return {
show: false,
};
},
watch: {
message() {
this.show = true;
setTimeout(() => {
this.show = false;
}, this.time);
},
},
};
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 999;
padding: 10px 20px;
border-radius: 5px;
color: #fff;
font-size: 14px;
text-align: center;
transition: opacity 0.3s ease-in-out;
}
.toast.info {
background-color: #2196f3;
}
.toast.success {
background-color: #4caf50;
}
.toast.warning {
background-color: #ff9800;
}
.toast.error {
background-color: #f44336;
}
</style>
```
2. 在需要使用的组件中引入自定义的 Toast 组件,并在该组件中定义一个方法来显示 Toast,例如:
```vue
<template>
<div>
<button @click="showToast">显示 Toast</button>
<Toast :message="toastMessage" :type="toastType" :time="toastTime" />
</div>
</template>
<script>
import Toast from '@/components/Toast.vue';
export default {
name: 'MyComponent',
components: {
Toast,
},
data() {
return {
toastMessage: '',
toastType: 'info',
toastTime: 3000,
};
},
methods: {
showToast() {
this.toastMessage = 'Hello, World!';
this.toastType = 'info';
this.toastTime = 3000;
},
},
};
</script>
```
在上面的代码中,我们定义了一个 `showToast` 方法来显示 Toast,该方法会设置 `toastMessage`、`toastType` 和 `toastTime` 三个属性的值,并将这些值传递给 Toast 组件进行显示。`toastTime` 属性用来指定 Toast 消失的时间,默认为 3000 毫秒。
当 `showToast` 方法被调用后,它会设置 `toastMessage`、`toastType` 和 `toastTime` 三个属性的值,并触发这些属性的 watch 函数。在 watch 函数中,我们设置 `show` 属性为 true,表示显示 Toast,同时使用 setTimeout 函数来在指定的时间后将 `show` 属性设置为 false,从而让 Toast 消失。
以上就是一个简单的自定义 Toast 的实现方式,你可以根据自己的需求进行修改和扩展。