问题:
在使用插槽的时候,插槽内的默认内容不显示出来。
如上图红框部分,没有使用插槽,按道理应该显示插槽中的默认内容,但是现在没有显示出来。
解决方法:
还未知
组件实现:
CountDown.vue
<template>
<div class="count_down-base">
<slot
:item="{
d: days,
h: hours,
m: mins,
s: seconds,
hh: `00${hours}`.slice(-2),
mm: `00${mins}`.slice(-2),
ss: `00${seconds}`.slice(-2),
}"
>
<span v-show="isIncludes('dd')">{{ days }}天</span>
<span v-show="isIncludes('hh')">{{ hours | zeroize }}:</span>
<span v-show="isIncludes('mm')">{{ mins | zeroize }}:</span>
<span v-show="isIncludes('ss')">{{ seconds | zeroize }}</span>
</slot>
</div>
</template>
<script>
export default {
filters: {
zeroize(val) {
if (val < 10) {
return '0' + val
}
return val
},
},
data: () => ({
days: '0',
hours: '00',
mins: '00',
seconds: '00',
timer: null,
clackCount_: 3,
curTime: 0,
}),
props: {
formatter: {
type: String,
default: 'dd天hh:mm:ss',
},
time: {
type: [Number, String],
default: 0,
},
// 时间时间单位是否为毫秒
isMilliSecond: {
type: Boolean,
default: false,
},
clackCount: {
// 重复执行次数,需要在 finishClick 方法中执行回调方法
type: Number,
default: 3,
},
},
computed: {
duration() {
const time = this.isMilliSecond
? Math.round(+this.time / 1000)
: Math.round(+this.time)
return time
},
},
watch: {
duration() {
this.countDown()
},
},
mounted() {
this.clackCount_ = this.clackCount
this.curTime = Date.now()
this.countDown()
},
methods: {
isIncludes(str) {
return this.formatter.includes(str)
},
countDown() {
this.getTime(this.duration)
},
getTime(duration) {
this.timer && clearTimeout(this.timer)
if (duration < 0) {
// 执行结束调用父组件方法,参数是重新执行倒计时回调函数,最多重新执行3次
this.$emit('finishClick', () => {
this.clackCount_ -= 1
if (this.clackCount_ < 0) {
return
}
this.getTime(this.duration)
})
return
}
const { dd, hh, mm, ss } = this.durationFormatter(duration)
this.days = dd || 0
this.hours = hh || 0
this.mins = mm || 0
this.seconds = ss || 0
this.timer = setTimeout(() => {
// 为什么使用diffTime?
// 部分浏览器在进入后台时(或者失去焦点时), 会将 setTimeout 等定时任务暂停 待用户回到浏览器时, 才会重新激活定时任务,这里要删除用户失去焦点时候与从新获得焦点的时间间隔
const now = Date.now()
const diffTime = Math.floor((now - this.curTime) / 1000)
this.curTime = now
this.getTime(duration - diffTime)
}, 1000)
},
durationFormatter(time) {
if (!time) return { ss: 0 }
let t = time
const ss = t % 60
t = (t - ss) / 60
if (t < 1) return { ss }
const mm = t % 60
t = (t - mm) / 60
if (t < 1) return { mm, ss }
const hh = t % 24
t = (t - hh) / 24
if (t < 1) return { hh, mm, ss }
const dd = t
return { dd, hh, mm, ss }
},
},
}
</script>
<style lang="scss" scoped>
.count_down-base {
display: flex;
justify-content: flex-start;
align-items: center;
}
</style>