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)
我在这种情况下使用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 相关
有不同的方法。
即时为每个人生成一个 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)| 归档时间: |
|
| 查看次数: |
14207 次 |
| 最近记录: |