vue 之 Toast插件的封装
toast/toast.vue
<!-- toast组件 -->
<template>
<div class="toast" :style="toastClass" v-show="isShowToast">{{ message }}</div>
</template>
<script>
export default {
name: "",
components: {},
data() {
return {
message: "",
isShowToast: false,
type: "success"
};
},
computed: {
toastClass() {
return this.type === "success" ? { color: "green" } : { color: "red" };
}
},
methods: {
show(message, duration = 1000, type = "success") {
this.isShowToast = true;
this.message = message;
this.type = type;
console.log("toast", this.type);
setTimeout(() => {
this.isShowToast = false;
}, duration);
}
}
};
</script>
<style lang="scss" scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
color: #fff;
background: rgba(150, 200, 112, 0.75);
z-index: 999;
}
</style>
toast/index.js
- toast插件的创建
import Toast from './toast.vue';
const obj = {}
obj.install = function (Vue) {
// 1:创建一个组件构造器 传入组件对象
const toastContrustor = Vue.extend(Toast);
// 2:使用new方式,根据组件构造器,可以创建出来一个组件对象
const toast = new toastContrustor();
// 3:将组件对象,手动的挂载到某一个元素身上
toast.$mount(document.createElement('div'));
// 4:toast.$el对应的就是div了 然后把这个对象添加到body之中!
document.body.appendChild(toast.$el);
Vue.prototype.$toast = toast;
}
export default obj;
main.js
toast插件的安装
import Toast from './components/toast/index';
//安装toast插件
Vue.use(Toast);
home.vue
toast插件的使用
<!-- -->
<template>
<div class="video-container">
视频
<button @click="showToast">显示toast</button>
</div>
</template>
<script>
export default {
name: "",
data() {
return {};
},
methods: {
showToast() {
this.$toast.show("我是成功的", 1000);
// this.$toast.show("我是失败的", 1000, "fail");
}
},
};
</script>