<script setup lang="ts">
import UserCommodityInfo from "@/store/home/commodity/Info.ts";
import { storeToRefs } from "pinia";
import CardChild from './CardChild/index.vue'
import { ref, onMounted } from "vue";
import { CountUp } from "countUp.js";
// 拿到服务器商品信息的数据
const UserCommodityInfos = UserCommodityInfo();
UserCommodityInfos.getReqCommodityInfo();
const { Reqdata } = storeToRefs(UserCommodityInfos);
let Count = ref<HTMLElement>();
onMounted(() => {
// 创建CountUp实例
const Countups = new CountUp(Count.value!, 1000);
console.log(Count.value);
// 开始执行
Countups.start();
});
</script>
<template>
<el-row justify="space-between" :gutter="10">
<template v-for="item in Reqdata" :key="item.amount">
<el-col :span="6">
<CardChild v-bind="item"></CardChild>
<span ref="Count">0</span>
</el-col>
</template>
</el-row>
</template>
<style scoped lang="less">
</style>
当span被包裹在el-col 中时代码中拿到的Count实例是undefined,如果将他抽成一个组件(CardChild)就不会出现拿不到实例对象(看上面代码)
CardChild组件:
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { CountUp } from "countUp.js";
const prop = defineProps({
title: {
type: String,
},
tips: {
type: String,
},
number1: {
type: Number,
},
number2: {
type: Number,
},
subtitle: {
type: String,
},
});
// ******变量******
// 获取需要执行CountUp的组件实例
let Count1 = ref<HTMLElement>();
let Count2 = ref<HTMLElement>();
onMounted(() => {
// 创建CountUp实例
const Countup1 = new CountUp(Count1.value!, prop.number1 ?? 0);
const Countup2 = new CountUp(Count2.value!, prop.number2 ?? 0);
// 开始执行
Countup1.start();
Countup2.start()
});
</script>
<template>
<div class="card">
<div class="head">
<h2>{{ title }}</h2>
<el-tooltip class="box-item" effect="light" :content="tips" placement="top">
<el-icon><Warning /></el-icon>
</el-tooltip>
</div>
<div class="conter">
<span ref="Count1">{{ number1 }}</span>
</div>
<div class="footer">
<h4 >{{ subtitle }} <span ref="Count2">{{ number2 }}</span></h4>
</div>
</div>
</template>
你在父组件中循环v-for使用ref(count)来引用元素,ref会有多个同名实例存在;
你抽取组件 每个子组件实例都会有它自己的ref实例,互不干扰 所以正常显示;