简体   繁体   中英

Append index dynamically to attribute

I have this button element:

<button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button>

it is generated dynamically inside a v-for loop. Instead of hard coding the attribute name like above vb-modal.modal-5 I want to concatenate it like this:

v-b-modal.modal-{{index}}

Is there a way to do this? I'm using vue-cli 3 and bootstrap-vue.

I haven't used this framework before but looking at the second example from the docs I think something like the following should work.

<button v-on:click="changeRecord(element)" v-b-modal="`modal-${index}`">Aendern</button>

You will need to ensure that the variable index is made available when you set up the v-for

EDIT: For clarity, the above works because in VueJS the input to a directive is evaluated as an expression. The above example uses backticks string interpolation but the same can be done using pretty much any valid expression like "'modal-'+index" or based on some property on the item we are looping over "`modal-${item.id}`" .

Unlike directives, class or other attributes are interpreted as plain strings unless they are bound using v-bind in which case they are treated as expressions. The example in the docs uses a simple string as an input so it's hard to tell from that particular example that it can be used in this way.

It is possible to add dynamic attributes like following

<p class="text" v-bind="options">{{ message }}</p>

Inside the computed , define the value for options

 export default {
  data:()=> {
    return {
      message: 'Hello world!',
      id: 12345
    }
  },
  computed: {
    options() {
      return {
        [`v-b-modal.modal-${this.id}`]: "whatever"
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM