javascript - 如何从 JSON 文件中的属性生成 Vue.js 中的唯一 ID?
问题描述
我正在使用 Vue.js 生成 div,并且我想使用 JSON 文件中的数据来执行此操作。
它不一定必须来自 JSON,但这会更好,我只需要在下面的 html 中为 div 的每个实例创建一个唯一的 id。
为每个 div 创建唯一 ID 的最佳方法是什么?
HTML
<ul>
<li v-for="(member, index) in cyclists" :key="index" class="col-md-4 inview fromBottomIn" data-in="fromBottomIn" data-out="fromBottomOut">
<div class="cycling__card">
<div class="cycling__rider-container">
<span class="cyclist__name">{{member.name}}</span>
</div>
<!-- Need to add id's to the div below -->
<div id={{member.name}}>
</div>
</div>
</li>
</ul>
JSON
"cyclists": [
{
"name": "Jason",
"position": "CEO",
},
{
"name": "Mike",
"position": "Digital Strategist",
},
{
"name": "Tom",
"position": "Vice President, Product Management",
},
{
"name": "Jeff",
"position": "Senior Director, Creative",
},
}
解决方案
我在这种情况下使用uuid,您需要将 json 数据合并到另一个具有新 id 的对象,因此示例:
<script>
import { uuid } from 'vue-uuid';
export default {
data() {
return {
uuid: uuid.v1(),
id: null
}
},
computed: {
newCyclists: function () {
const id = this.id;
const newID = this.$uuid.v4();
return {
...cyclists,
id: newID,
}
}
}
};
</script>
在computed
使用扩展运算符将新 ID 与具有新 ID 的当前 JSON 数据合并时,vue-uuid
来自uuid库,v4 与生成 ID 相关
推荐阅读
- linux-kernel - 用户缓冲区是否可以始终映射到连续的内核虚拟地址?
- python - 仅绘制正加权边 NetworkX
- amazon-web-services - INACTIVE 任务 - 如何杀死他们
- python - Python 正则表达式拆分
- python - 图工具:如何找到适合某个属性值的顶点?
- c# - 查询嵌套实体集合
- python - python StanfordDependencyParser 输出退出代码 0
- reactjs - 将 Uber api 集成到 react-native
- python - 打开 Spyder Ubuntu 时出错
- python - 通过过滤单列从数据框中删除异常值