首页 > 解决方案 > 如何从 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",
    },
}

标签: javascriptjsonvue.jsvue-component

解决方案


我在这种情况下使用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 相关


推荐阅读