您的位置:首页 > 汽车 > 时评 > 网络游戏排行榜2022_自己怎么做小程序接单_互动营销的概念_志鸿优化网

网络游戏排行榜2022_自己怎么做小程序接单_互动营销的概念_志鸿优化网

2025/5/10 6:33:46 来源:https://blog.csdn.net/kfei666/article/details/146545130  浏览:    关键词:网络游戏排行榜2022_自己怎么做小程序接单_互动营销的概念_志鸿优化网
网络游戏排行榜2022_自己怎么做小程序接单_互动营销的概念_志鸿优化网
<template><div><!-- 假设这里有多个 div 元素,通过 v-for 循环生成 --><div v-for="index in 10" :key="index" :ref="(el) => setref({el, index})">这是第 {{ index }} 个 div 元素</div><button @click="addClassNameToElement('field1', 'active')">为第 1 个元素添加类名</button></div>
</template><script setup>
import { useSlideState } from './slideState.js';const slideStateStore = useSlideState();// 定义 setref 函数
const setref = (data) => {slideStateStore.setElementRef(data);
};// 为指定字段对应的元素添加类名
const addClassNameToElement = (field, className) => {slideStateStore.addClassToElement(field, className);
};
</script><style scoped>
.active {color: red;
}
</style>
import { defineStore } from 'pinia';export const useSlideState = defineStore('slideState', {state: () => ({elementRefs: {}}),actions: {setElementRef(data) {const { el, index } = data;const field = `field${index}`;this.elementRefs[field] = el;},getElementRef(field) {return this.elementRefs[field];},addClassToElement(field, className) {const element = this.elementRefs[field];if (element) {element.classList.add(className);}}}
});

代码解释

  • Pinia 存储:setElementRef 方法接收一个包含 el 和 index 的对象,从对象中提取 el 和 index,并使用 index 生成字段名,将 el 存储到 elementRefs 对象中。
  • 组件:通过 v-for 循环生成多个 div 元素,每个 div 元素的 :ref 绑定一个箭头函数,将包含 el 和 index 的对象传递给 setref 函数。setref 函数将这个对象传递给 Pinia 存储中的 setElementRef 方法。

通过这种方式,你可以将包含 el 和 index 的对象传递给 setref 函数,并正确存储和使用这些 ref。

但是请注意,如果是elementUI元素的ref,在获取el时,需要用el.$el。这个很关键。要不然报错。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com