vue 封装一个toast组件
第一步 创建一个toast.vue
<template>
<transition name="fade">
<div v-show="visible">{{message}}</div>
</transition>
</template>
<script>
export default {
data () {
return {
visible: false,
message: ''
}
}
}
</script>
<style scoped>
div {
padding: 15px 30px;
color: #fff;
background-color: rgba(0, 0, 0, 0.6);
text-align: center;
position: fixed;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
}
.fade-enter-active,
.fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
第二步 创建一个index.js
import ToastComponent from './toast.vue'
const Toast = {
install: function (Vue) {
const ToastConstructor = Vue.extend(ToastComponent)
const instance = new ToastConstructor()
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
Vue.prototype.$toast = (msg, duration = 1500) => {
instance.message = msg
instance.visible = true
setTimeout(() => {
instance.visible = false
}, duration)
}
}
}
export default Toast
第三步 main.js
import Toast from './components/toast/index'
Vue.use(Toast)
第四步:在组件中使用
<template>
<div class="home">
<button @click="go">点击</button>
</div>
</template>
<script>
export default {
name: "Home",
components: {},
data: function() {
return {};
},
mounted() {},
methods: {
go() {
this.$toast("加载中");
}
}
};
</script>
<style scoped>
.home {
width: 100%;
height: 100vh;
background-color: pink;
}
</style>