简体   繁体   English

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

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

I am using Vue.js to generate divs and I would like to use data from a JSON file to do so. 我正在使用Vue.js生成div,我想使用JSON文件中的数据来实现。

It doesn't necessarily have to be from the JSON but that would be preferable, I just need to create a unique id for each instance of the div in the html below. 它不一定必须来自JSON,但这是更好的选择,我只需要在下面的html中为div的每个实例创建一个唯一的ID。

What is the best way to create unique ID's for each of the divs? 为每个div创建唯一ID的最佳方法是什么?

HTML 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 JSON

  "cyclists": [
    {
      "name": "Jason",
      "position": "CEO",
    },
    {
      "name": "Mike",
      "position": "Digital Strategist",
    },
    {
      "name": "Tom",
      "position": "Vice President, Product Management",
    },
    {
      "name": "Jeff",
      "position": "Senior Director, Creative",
    },
}

I'm in this case using uuid , you will need to merge json data to another object wit new id, so the example: 我在这种情况下使用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>

in computed using spread operator to merge new ID with current JSON data with a new ID, vue-uuid come from uuid library and v4 is related to generate ID's 在使用传播运算符进行computed以将新ID与当前JSON数据与新ID合并后, vue-uuid来自uuid库,而v4与生成ID有关

If you didn't want to load in an additional module like vue-uuid you could use this function to generate a hash of the result of stringifying each array object on the assumption that each name/position will be unique. 如果您不想加载像vue-uuid这样的附加模块,则可以使用此函数来生成将每个数组对象字符串化的结果的哈希值,前提是每个名称/位置都是唯一的。

I've used this Stackoverflow answer as the basis of this one. 我已将这个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); 

Then you can loop over the data as you would normally. 然后,您可以像往常一样遍历数据。

There are different approaches. 有不同的方法。

  1. Use an index. 使用索引。 You have an array, so just use the index they come from, prepended with something unique to the object. 您有一个数组,因此只需使用它们来自的索引,并以该对象特有的前缀即可。 cyclist_1, cyclist_2... cyclist_1,cyclist_2 ...
  2. Put the ids on the JSON as part of the data. 将ID作为数据的一部分放在JSON上。
  3. Derive it from the data you have. 从您拥有的数据中得出。 With a hash, or simply concatenating name + position. 使用散列,或简单地将名称+位置连接在一起。 Use some function to sanitise it (remove spaces, invalid html characters, etc.) 使用一些功能对其进行清理(删除空格,无效的html字符等)
  4. Generate a uuid for each one on the fly. 即时为每个人生成一个uuid。 You can use this amazing function for uuid version 4 developed by the community to be the shortest possible: 您可以将此惊人的功能用于社区开发的 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