先看效果
分析案例
插件
Vue-count-to
- 安装
npm install vue-count-to 来安装vue-count-to插件
- API说明
| Property | Description | type | default |
|---|---|---|---|
| startVal | 开始值 | Number | 0 |
| endVal | 结束值 | Number | 2017 |
| duration | 持续时间 | Number | 3000 |
| autoplay | 自动播放 | Boolean | true |
| decimals | 要显示的小数位数 | Number | 0 |
| decimal | 十进制分割 | String | . |
| separator | 分隔符 | String | , |
| prefix | 前缀 | String | '' |
| suffix | 后缀 | String | '' |
| useEasing | 使用缓和功能 | Boolean | true |
| easingFn | 缓和回调 | Function | — |
功能
| Function Name | Description |
|---|---|
| mountedCallback | 挂载以后返回回调 |
| start | 开始计数 |
| pause | 暂停计数 |
| reset | 重置CountTo |
- 导入插件并声明
<script>
import countTo from 'vue-count-to' // 导入插件
export default{
components: { countTo }, // 声明使用
}
</script>
- 使用插件
<template>
<div class="content-count" id="countToWrapper">
<div class="count-inner" v-for="item in dataMsg" :key="item.id">
<countTo :startVal="0" ref="countTos" :endVal="item.value" :duration="3000"> </countTo>
<span>+</span>
<p>{{ item.item }}</p>
</div>
</div>
</template>
// dataMsg是我接口获取到的数据,v-for进行遍历。
// 写道这里我们数字滚动就可以实现。
// 那么如何实现页面滚动时候,数字也滚动呢?
// 下面接着讲要用一个 IntersectionObserver属性
异步监听目标元素 IntersectionObserver
解读属性
监听目标元素与其祖先或视窗交叉状态的手段,其实就是观察一个元素是否在视窗可见
运用场景:
- 当页面滚动时,懒加载图片或其他内容。
- 实现“可无限滚动”网站,也就是当用户滚动网页时直接加载更多内容,无需翻页。
- 对某些元素进行埋点曝光
- 滚动到相应区域来执行相应动画或其他任务。
mounted(){
// 创建实例 循环调用 所有 dom
const io = new IntersectionObserver((entries) => {
// entries 实际上是dom
// 将其转为数组,遍历
Array.from(entries).forEach((item) => {
if (item.intersectionRatio > 0.1) {
// intersectionRatio 相交区域和目标元素的比例值
// intersectionRect/boundingClientRect 不可见时小于等于0
// intersectionRatio和isIntersecting是用来判断元素是否可见的
const countTos = this.$refs.countTos
// 通过$refs获取实例,遍历调用实例方法start()
countTos.map((counto) => {
counto.start()
})
}
})
})
// 获取所有 countToWrapper 标签 开始观察
const countToWrapper = document.getElementById('countToWrapper')
io.observe(countToWrapper)
}
DEMO演示
总结
主要用到Vue-count-to这个数字滚动插件,其次是IntersectionObserver属性来做一个异步监听