0

I am trying to think of a way to add more than one attribute dynamically. Below is a mockup code for that. If I loop through attributes and try to add it to img tag then I'll have more than one image tag and that I don't want. I want to have all the attributes inside the array to be on the same element.

Any help would be appreciated.

<template>
  <img />
</template>

<script>
export default {
 data(){
  attributes: [
    {class: 'main'},
    {src: '/somthing/img.jpg'}
  ]
 }
}
</script>

1 Answer 1

1

You can use v-bind for that purpose. Example:

<template>
  <img v-bind="attributes"/>
</template>

<script>
export default {
 data(){
  return {
    attributes: {
      class: 'main',
      src: '/somthing/img.jpg'
    }
  }
 }
}
</script>

If you would like to also dynamicly bind event's listeners you could use v-on same way as I did with v-bind

Sign up to request clarification or add additional context in comments.

6 Comments

I don't want to add every attribute myself. I want to loop through it and add them all dynamically.
My method adds each attribute from an array to img tag just with one v-bind. You do not have to bind each key. Didn't you need exactly that?
But you are not looping through the attributes array ?
I modified the code in the response. Check it now. It does not require an array
So basically, v-bind loops through the object itself and adds the attributes ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.