如何通过JSON文件中的属性在Vue.js中生成唯一ID? [英] How can I generate unique id's in Vue.js from attributes in a JSON file?

查看:245
本文介绍了如何通过JSON文件中的属性在Vue.js中生成唯一ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue.js生成div,我想使用JSON文件中的数据来实现.

I am using Vue.js to generate divs and I would like to use data from a JSON file to do so.

它不一定必须来自JSON,但这是更好的选择,我只需要在下面的html中为div的每个实例创建一个唯一的ID.

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.

为每个div创建唯一ID的最佳方法是什么?

What is the best way to create unique ID's for each of the divs?

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的对象,因此示例如下:

I'm in this case using uuid, you will need to merge json data to another object wit new id, so the example:

<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来自

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

这篇关于如何通过JSON文件中的属性在Vue.js中生成唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆