支持 this.$toast.error()
这里我们打算支持 this.$toast.error() 和 this.$toast.success() 这两种方式,所以我们第一步还是要先去修改一下 main.vue 文件的内容(主要就是根据 type 值来修改组件的样式),就像下面这样:
<!--main.vue-->
<template>
<div class="toast" :class="type ? `toast--${type}` : ''">
<p>{{ content }}</p>
</div>
</template>
<script>
export default {
...
data() {
return {
type: "",
content: "",
duration: 3000
};
},
...
};
</script>
<style lang="scss" scoped>
.toast {
...
&--error p { background: rgba(255, 0, 0, 0.5); }
&--success p { background: rgba(0, 255, 0, 0.5); }
}
</style>其次,this.$toast.error() 其实就等价于 Toast.error(),所以我们现在的目的就是要给 Toast 函数扩充方法,也比较简单,就先看代码再解释吧:
// main.js
const Toast = function(options = {}) {
...
};
// 以下就是在 Toast 函数中拓展 ["success", "error"] 这两个方法
["success", "error"].forEach(type => {
Toast[type] = options => {
options.type = type;
return Toast(options);
};
});
export default Toast;我们可以看到 Toast.error() 和 Toast.success() 最终还是调用 Toast(options) 这个函数,只不过在调用之前需要多做一步处理,就是将 [“success”, “error”] 作为一个 type 参数给合并进 options 里面再传递,仅此而已😬。
那就试试效果吧:
<script>
export default {
methods: {
showToast() {
this.$toast({ content: "这是正常的" });
},
showErrorToast() {
this.$toast.error({ content: "竟然失败了" });
},
showSuccessToast() {
this.$toast.success({ content: "居然成功了" });
}
}
};
</script>
大赞无疆,大。赞。。无。。。疆。。。。。👍
结语
至此,一个通过 js 调用的简单 toast 组件就搞定啦,短短的几行代码还是挺考验 js 功底的💪。当然这只是个超简易版的 demo,显然不够完善和健壮,所以我们可以在此基础上扩充一下,比如当 duration <= 0 的时候,我们让这个 toast 一直显示,然后扩展一个 close 方法来关闭等等之类的。不过还是那句老话,实践才是检验真理的唯一标准。纸上得来终觉浅,绝知此事要躬行。step by step, day day up ! 🎉 🎉 🎉










