簡體   English   中英

如何通過JSON文件中的屬性在Vue.js中生成唯一ID?

[英]How can I generate unique id's in Vue.js from attributes in a JSON file?

我正在使用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與當前JSON數據與新ID合並后, vue-uuid來自uuid庫,而v4與生成ID有關

如果您不想加載像vue-uuid這樣的附加模塊,則可以使用此函數來生成將每個數組對象字符串化的結果的哈希值,前提是每個名稱/位置都是唯一的。

我已將這個Stackoverflow答案用作此答案的基礎。

 const data = [{"name":"Jason","position":"CEO"},{"name":"Mike","position":"Digital Strategist"},{"name":"Tom","position":"Vice President, Product Management"},{"name":"Jeff","position":"Senior Director, Creative"}]; function genHash(str) { var hash = 0, i, chr; if (str.length === 0) return hash; for (i = 0; i < str.length; i++) { chr = str.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; } return hash; }; // For each object in the array create // a stringyfied version of it and create // a hash data.forEach(obj => { obj.id = genHash(JSON.stringify(obj)); }); console.log(data); 

然后,您可以像往常一樣遍歷數據。

有不同的方法。

  1. 使用索引。 您有一個數組,因此只需使用它們來自的索引,並以該對象特有的前綴即可。 cyclist_1,cyclist_2 ...
  2. 將ID作為數據的一部分放在JSON上。
  3. 從您擁有的數據中得出。 使用散列,或簡單地將名稱+位置連接在一起。 使用一些功能對其進行清理(刪除空格,無效的html字符等)
  4. 即時為每個人生成一個uuid。 您可以將此驚人的功能用於社區開發的 uuid版本4 以使其盡可能最短:

     function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM