directives/index.js
// 数字滚动增长自定义指令
export const scrollNumber = {
mounted(el, binding) {
let timer = null;
const target = Number(binding.value);
const duration = 1000; // 持续时间为 1 秒钟
const step = Math.ceil(target / (duration / 16)); // 步长为总距离除以时间
let current = 0;
timer = setInterval(() => {
current += step;
if (current >= target) {
current = target;
clearInterval(timer);
}
el.innerHTML = current.toLocaleString(); // 用 toLocaleString 将数值格式化为千分位表示
}, 16); // 每隔 16 毫秒变化一次
},
unmounted() {
clearInterval(timer);
},
};
main.js
import { createApp } from "vue";
import router from "@/router/index.js";
import "@/styles/index.scss";
import { scrollNumber } from "@/directives";
import App from "./App.vue";
const app = createApp(App);
app.directive("scroll-number", scrollNumber);
app.use(router);
app.mount("#app");