背景:
在前端項(xiàng)目開發(fā)中,我們除了日常使用的vant庫,還經(jīng)常會根據(jù)業(yè)務(wù)自己去封裝一些組件庫。這樣即會使得我們的代碼可復(fù)用,又提高了我們的開發(fā)效率。
以最簡化的Toast組件舉例:
/components/toast.vue
<template lang="pug">
.app(v-show='show')
span {{ msg }}
</template>
<script>
export default {
name: 'toast',
props: {
show: {
type: Boolean,
default: false
},
msg: {
type: String,
default: '提示'
},
duration: {
type: Number,
default: 2000
}
},
data: {
timerDuration: null
},
watch: {
show(n) {
if (!n && this.timerDuration) {
clearTimeout(this.timerDuration)
this.timerDuration = null
}
}
},
methods: {
init() {
this.show = true
this.timerDuration = setTimeout(() => {
this.show = false
}, this.duration)
},
clear() {
this.show = false
}
}
}
</script>
<style lang="scss" scoped>
.app {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 160px;
height: 40px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
span {
display: block;
color: #fff;
font-size: 14px;
}
}
</style>
/common/toast.js
import Toast from '@/components/toast.vue'
let ConfirmConstructor, instance
const showToast = {
install(Vue) {
ConfirmConstructor = Vue.extend(Toast)
instance = new ConfirmConstructor().$mount()
document.body.appendChild(instance.$el)
Vue.prototype.$showToast = options => {
Object.assign(instance, options)
instance.init()
}
Vue.prototype.$showToast.clear = () => {
instance.clear()
}
}
}
export default showToast
/main.js
import ShowToast from './common/toast'
Vue.use(ShowToast)
/views/demo.vue
// 展示toast
this.$showToast({
msg: '網(wǎng)絡(luò)錯(cuò)誤',
duration: 1000
})
// 清除toast
this.$showToast.clear()
備注
基于上面最簡化的demo,我們可以再豐富此組件亦可創(chuàng)造其他組件。