Home > Mobile >  How to refer to specific dinamicly added comonent form number of dinamycly added components in Vue,
How to refer to specific dinamicly added comonent form number of dinamycly added components in Vue,

Time:01-12

What or where is idivdual id or any other element that i can call to run a function on component.

Example: Useing add button i'm ceating dynamicly colored squeres. Each squere has close buton. Then i want to delate one of squers. Let say blue one (third child of template).

v-bind:id='var' doesn't works because then all squers heve same id.

CodePudding user response:

You can use ref, you can define ref in every added component. The ref is array. you can refrence component through index of the ref. for example;<div v-for="(item) in arr" :key="item.id"> <span ref="testRef"> item.name </span> </div>, you can use 'this.$refs.testRef[index]' find component which you want.

CodePudding user response:

There are multiple options. For instance, in your v-for loop you can get the index this way: (official docs)

<div v-for="(item, index) in myList" :key="index">
    {{ item.name }}
</div>

You could then for example use the index in a ref to access the element for the script.

Another option is to pass the event instance to the onclick listener with the special keyword $event, and use this to get the element:

<div ... @click="myFunction($event)">
    {{ item.name }}
</div>

And then in your script

myFunction(ev) {
  // do something with the element that was clicked on
  console.log(ev.target)
}

However, a more 'vue' way would be to not mess with the elements, but only manipulate the underlying data and let vue worry about representing the data with elements on your page. For instance, you could make your squares be represented by a list of objects, containing their own data own the state (opened or closed). So in your script you have:

data() {
  return {
    squares: [
      { color: "ff0000", opened: true },
      ...
    ]
  }
},

And in your template something like

<div
    v-for="square in squares"
    v-show="suare.opened"
    @click="square.opened = false" 
> ... 
  •  Tags:  
  • Related