1、組件封裝基礎
npm install countup@latest
2、組件中使用id值
3、組件中獲得dom
如何封裝一個組件,在組件中用到需要傳入HTML元素ID值的JS庫時如何處理,如何獲取一個DOM或一個組件實例,插槽、$nextTick、生命周期
<template>
<div>
<slot name="left"></slot><span ref="number" :class="countClass" :id="eleId"></span><slot name="right"></slot>
</div>
</template>
<script>
import CountUp from 'countup'
export default {
name: 'CountTo',
computed: {
eleId () {
return `count_up_${this._uid}`
},
countClass () {
return [
'count-to-number',
this.className
]
}
},
data () {
return {
counter: {}
}
},
props: {
/**
* @description 起始值
*/
startVal: {
type: Number,
default: 0
},
/**
* @description 最終值
*/
endVal: {
type: Number,
required: true
},
/**
* @description 小數點后保留幾位小數
*/
decimals: {
type: Number,
default: 0
},
/**
* @description 動畫延遲開始時間
*/
delay: {
type: Number,
default: 0
},
/**
* @description 漸變時長
*/
duration: {
type: Number,
default: 1
},
/**
* @description 是否使用變速效果
*/
useEasing: {
type: Boolean,
default: false
},
/**
* @description 是否使用變速效果
*/
useGrouping: {
type: Boolean,
default: true
},
/**
* @description 分組符號
*/
separator: {
type: String,
default: ','
},
/**
* @description 整數和小數分割符號
*/
decimal: {
type: String,
default: '.'
},
className: {
type: String,
default: ''
}
},
methods: {
getCount () {
console.log(this.$refs.number.innerText)
return this.$refs.number.innerText
},
emitEndEvent () {
setTimeout(() => {
this.$nextTick(() => {
this.$emit('on-animation-end', Number(this.getCount()))
})
}, this.duration * 1000 + 20)
}
},
watch: {
endVal (newVal, oldVal) {
this.counter.update(newVal)
this.emitEndEvent()
}
},
mounted () {
this.$nextTick(() => {
this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimals, this.duration, {
useEasing: this.useEasing,
useGrouping: this.useGrouping,
separator: this.separator,
decimal: this.decimal
})
setTimeout(() => {
this.counter.start()
this.emitEndEvent()
}, this.delay)
})
}
}
</script>
<style lang="less">
@import './count-to.less';
</style>
