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

SBT*_*434 5 javascript json vue.js vue-component

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

JSON

  "cyclists": [
    {
      "name": "Jason",
      "position": "CEO",
    },
    {
      "name": "Mike",
      "position": "Digital Strategist",
    },
    {
      "name": "Tom",
      "position": "Vice President, Product Management",
    },
    {
      "name": "Jeff",
      "position": "Senior Director, Creative",
    },
}
Run Code Online (Sandbox Code Playgroud)

Mou*_*man 9

我在这种情况下使用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>
Run Code Online (Sandbox Code Playgroud)

computed使用扩展运算符将新 ID 与具有新 ID 的当前 JSON 数据合并时,vue-uuid来自uuid库和 v4 与生成 ID 相关


jor*_*edo 6

有不同的方法。

  1. 使用索引。您有一个数组,因此只需使用它们来自的索引,并在前面加上该对象特有的内容。骑自行车者_1、骑自行车者_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)}
    
    Run Code Online (Sandbox Code Playgroud)