第一步:编写组件
<template>
<div class="toast" v-show="isShow">
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name: 'Toast',
data () {
return {
isShow: false,
message: ''
}
},
methods: {
show (message, duration) {
this.isShow = true
this.message = message
setTimeout(() => {
this.isShow = false
}, duration)
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
padding: 8px 10px;
transform: translate(-50%, -50%);
color: #fff;
background-color: rgba(0, 0, 0, 0.75);
}
</style>
第二步: 在组件目录中新增index.js文件,注册是直接找改文件
import Toast from './Toast'
const toast = {
install(vue) {
vue.component('toast', Toast)
}
}
export default toast
第三步:在main.js中注册组件
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import toast from 'components/common/toast'
const app = createApp(App)
app.use(store).use(router).use(toast).mount('#app')
第四步:使用组件
<toast ref="toast" :message="message" :show="show"></toast>
this.$refs.toast.show(res, 1500)