自定义了一个插件,有两个方法:.show()
创建插件并显示.hide()
销毁指定插件
代码:
toast/toast.vue
<template>
<div id="toast">
<p v-show="show">
{{msg}}
</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: ''
}
}
}
</script>
toast/index.js
import ToastComponent from './toast.vue'
const Toast = {}
// 注册Toast
Toast.install = (Vue) => {
const ToastConstructor = Vue.extend(ToastComponent)
Vue.prototype.$toast = {
show(msg) {
const instance = new ToastConstructor()
instance.$mount()
document.body.appendChild(instance.$el)
instance.show = true
instance.msg = msg
//这里return整个实例感觉不太好,不知如何改进
return instance
},
hide(instance) {
instance.$destroy()
document.body.removeChild(instance.$el)
}
}
}
export default Toast
其他组件中使用:
let t1 = this.$toast.show('msg') //显示
this.$toast.hide(t1) //销毁
let t2 = this.$toast.show('msg2') //显示
this.$toast.hide(t2) //销毁
现在我有点不解的是,在show()
方法中我选择return
整个实例来达到调用hide()
方法的时候可以传入这个实例,然后在hide()
方法中调用实例的$destroy()
进行销毁。
但是我总觉得直接return
整个实例的做法好像不太好,所以想请问下我这个代码该如何改进一下?
按照正常组件的设计来说,在
show
方法中return
实例是正常操作,并没有什么不好。我觉得你这个设计的缺点是在
hide
上,正常来说hide
方法应该是直接写在实例上的而不是再通过全局
hide
方法去关闭,而全局hide
方法可以用来不需参数即关闭当前打开的所有toast
,这可以简单通过在show
方法里面全局缓存instance
来实现。