简体   繁体   中英

How to bind dynamic id in Vue.JS HTML tag

I am using Bootstrap Vue for UI & trying to use collapse by this link

https://bootstrap-vue.js.org/docs/components/collapse/#usage

like vb-toggle.collapse-2 and the 2 is id I know & statically it's fine but I want to dynamic this id based on DB record like DB id & look at the below I am trying to do that like

<h3 v-b-toggle.collapse-{{data.id}}>Show</h3>

but {{data.id}} not working it's showing exactly which like {{data.id}} . How to I do that to compile variable data.id in h3 tag.

Thanks

Based on the documentation, the vb-toggle attribute accepts a JS expression of a string value, ie:

<!-- Using value -->
<b-button v-b-toggle="'collapse-2'" class="m-1">Toggle Collapse</b-button>

If that's the case, then it is simply a matter of binding a method to it:

<h3 v-bind:v-b-toggle="getTarget(data.id)">Show</h3>

methods: {
    getTarget(id) {
        return `'collapse-${id}'`;
    }
}

Try this.

<div>
  <!-- Using modifiers -->
  <b-button v-b-toggle="'collapse-2'" class="m-1">Toggle Collapse</b-button>

  <!-- Using value -->
  <b-button v-b-toggle="'collapse-2'" class="m-1">Toggle Collapse</b-button>

  <!-- Element to collapse -->
  <b-collapse id="collapse-2">
    <b-card>I am collapsible content!</b-card>
  </b-collapse>
</div>

codepen - https://codepen.io/Pratik__007/pen/YzXxGQK

Wrap the h3 tag inside a div or span and set the innerHTML of that div to be the content of the h3 tag but compiled inside a function.

const generateH3 = (id) => `<h3 v-b-toggle.collapse-${data.id}>Show</h3>` 
<div v-html='generateH3(data.id)'></div>

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