上代码:
<template>
<span :class="commonClass" :style="commonStyle">
<span :class="selfClass" :style="selfStyle" :id="countId">{{ initCount }}</span>
</span>
</template>
<script>
import CountUp from 'countup'
export default {
data () {
return {
count: {},
countId: 'count' + parseInt(Math.random() * 1000000)
}
},
props: {
// 公用的class
commonClass: {
type: String,
default: ''
},
// 公用的style
commonStyle: {
type: Object,
default: () => {
return {
fontSize: '30px',
color: '#dc9387'
}
}
},
// 私有的class
selfClass: {
type: String,
default: ''
},
// 私有的style
selfStyle: {
type: Object
},
// 初始的默认值
initCount: {
type: Number,
default: 0
},
// 旧值
oldValue: {
type: Number,
default: 0
},
// 新值
newValue: {
type: Number,
default: 0
},
// 保留小数位数
decimals: {
type: Number,
default: 0
},
// 完整动画过渡的时间,单位秒
duration: {
type: Number,
default: 2
},
// 是否线性过渡变化,false为是
useEasing: {
type: Boolean,
default: false
},
// 是否每三位数字用符号标识
useGrouping: {
type: Boolean,
default: true
},
// 标识的符号
separator: {
type: String,
default: ','
},
// 小数的符号
decimal: {
type: String,
default: ','
},
// 前置展示的文字
prefix: {
type: String,
default: ''
},
// 后置展示的文字
suffix: {
type: String,
default: ''
},
// 延迟开始过渡动画时间,单位毫秒
delay: {
type: Number,
default: 0
}
},
methods: {
},
mounted () {
this.$nextTick(() => {
setTimeout(() => {
this.count = new CountUp(this.countId, this.oldValue, this.newValue, this.decimals, this.duration, {
useEasing: this.useEasing,
useGrouping: this.useGrouping,
separator: this.separator,
decimal: this.decimal,
prefix: this.prefix,
suffix: this.suffix
});
if (!this.count.error) {
this.count.start();
} else {
console.error(this.count.error);
}
}, this.delay)
})
},
watch: {
'newValue' (val) {
this.count.update(val)
}
}
}
</script>
打开页面数据展示倒是没什么问题,但是一直报错Error in callback for watcher "newValue": "TypeError: this.count.update is not a function"
这是为什么?
另:现在要做的效果是一个接口返回所有数据复用几次这个组件,然后有各自的延迟,但是我这么写实际测了下只有第一次是有延迟的,等到第二次调接口返回数据,所有歌计数都同时开始改变了,这该怎么写?
第一点是'newValue'引号问题;
第二点是watch那个this.count执行次序在setTimeout之后,所以首次执行并没有new CountUp成功,解决方法是要么忽略报错并不影响使用,要么在watch那里直接再new一次CountUp取得里面的update方法,这个应该是iview admin里面封装的一个组建,用它的脚手架并不会报错,这点还得请iview作者Aresn大神来分析了。
之前的方法有点问题,还有一个办法是在watch那里写个延迟