Vue.js : How to set a unique ID for each component

2020-02-16 07:19发布

I want to create a component with Vue.js containing a label and an input. for example :

<label for="inputId">Label text</label>
<input id="inputId" type="text" />

How can I set a unique ID for each component instance?

Thank you.

标签: vue.js
10条回答
该账号已被封号
2楼-- · 2020-02-16 07:58

This package seems to be a good solution for the underlying issue of having non-unique IDs in your DOM across multiple components:

vue-uniq-ids

It is a trend to use components. Components are cool, they are small, obvious, easy to use and modular. Untill it comes to the id property.

Some HTML tag attributes requires using an id property, like label[for], input[form] and many of aria-* attributes. And the problem with the id is that it is not modular. If several id properties on the page will has the same value they can affect each other.

VueUniqIds helps you to get rid of this problem. It provides the set of id-related directives which value is automatically modified by adding unique string while keeping the attrbitue easy to read.

查看更多
够拽才男人
3楼-- · 2020-02-16 07:59

It can also be achieved using this pattern (Vue 2.0 v-bind) , so let say you have a list of items to iterate over and you want to give some dom element uninque id's.

new Vue({

  el:body,
  data: {
     myElementIds : [1,2,3,4,5,6,8]
   }
})

Html

<div v-for="id in myElementIds">
    <label v-bind:for="id">Label text for {{id}}</label>
    <input v-bind:id="id" type="text" />
<div> 

Hope it helps

查看更多
爷的心禁止访问
4楼-- · 2020-02-16 08:02

Each component has a unique id which can be accessed as this._uid.

<template>
  <div>
    <label :for="id">Label text for {{id}}</label>
    <input :id="id" type="text" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      id: null
    }
  }, 
  mounted () {
    this.id = this._uid
  }
}
</script>

If you want more control over the ids you can for example, generate them inside a parent component.

查看更多
Explosion°爆炸
5楼-- · 2020-02-16 08:04

To Nihat's point (above): Evan You has advised against using _uid: "The vm _uid is reserved for internal use and it's important to keep it private (and not rely on it in user code) so that we keep the flexibility to change its behavior for potential future use cases. ... I'd suggest generating UIDs yourself [using a module, a global mixin, etc.]"

Using the suggested mixin in this GitHub issue to generate the UID seems like a better approach:

let uuid = 0;

export default {
  beforeCreate() {
    this.uuid = uuid.toString();
    uuid += 1;
  },
};
查看更多
登录 后发表回答