1

I am a beginner.

I am trying to dynamically add id in my href tag but it is not working.

Here is my code.

  <div class="col-md-6"  v-for="Product in data">
      <div class="panel panel-default" >
          <div class="panel-heading">
              {{ Product.name }}
          </div>
          <div class="panel-body" v-for = "Category in Product.Categories">
              <div class="panel-group" id="accordion">
                  <div class="panel panel-default">
                      <div class="panel-heading">
                          <h4 class="panel-title">

                              <!--SEE HREF BELOW -->
                              <a data-toggle="collapse" data-parent="#accordion" href="#{{Category._id}}"  >
                                   {{ Category.name }}</a>
                           </h4>
                       </div>

                       <!-- SEE ID BELOW AS WELL -->
                       <div id="{{ Category._id }}" class="panel-collapse collapse">
                           <div class="panel-body"></div>
                       </div>
                 </div>
            </div>    
       </div>
 </div>

I am trying to give _id to href in <a data-toggle="collapse" data-parent="#accordion" href="#{{Category._id}}"> and in href I am giving Id of <div id="{{ Category._id }}" class="panel-collapse collapse"> tag on above href.

How can I do this?

Thanks

Pavel
  • 1,519
  • 21
  • 29
Awais Azmat
  • 9
  • 1
  • 3

2 Answers2

2

Try this out: :href="`#${Category._id}`"

The colon tells Vue to interpret the value as JavaScript, not a string. The backticks are doing string interpolation so you can have the preceding hash.

Ben
  • 2,962
  • 2
  • 20
  • 26
0

You can't use interpolation in vue 2, you need to bind your properties to some data object or computed using v-bind (or the colon shorthand) for:

<a data-toggle="collapse" data-parent="#accordion" href="#{{Category._id}}"  >

I would use a computed:

new Vue({
  el: '#app',
  computed:{
    href(){
      return '#' + this.Category._id
    }
  },
  data(){
    return {
      Category: {
        _id: 1
      }
    }
  }
})

You would then do:

<a data-toggle="collapse" data-parent="#accordion" v-bind:href="href">

Here's a JSFiddle to show you: https://jsfiddle.net/ym29dd2n/

For:

<div id="{{ Category._id }}" class="panel-collapse collapse">

it's the same thing but you can just bind the id directly:

<div v-bind:id="Category._id" class="panel-collapse collapse">
tony19
  • 125,647
  • 18
  • 229
  • 307
craig_h
  • 31,871
  • 6
  • 59
  • 68