string interpolation Vue js

16,198

Solution 1

You can inline it as stated by Vamsi, but you can also use a computed, which has a bit of a neater syntax:

Markup

<div :id="collapse_id"></div>

View Model

computed: {
  collapse_id() {
    return 'collapse_' + this.thread_ref
  }
},

However, that relies on thread_ref being available in data, here's the JSFiddle: https://jsfiddle.net/j9s3zhp2/

If it being placed inside a v-for you can achieve the same with a method:

Markup

<div v-for="ref in refs"> 
  <div :id="collapse_id(ref)"></div>
</div>

View Model

methods:{
  collapse_id(thread_ref){
    return 'collapse_' + thread_ref
  }
}

And here's the JSFiddle for that: https://jsfiddle.net/5o1dp7w5/

Solution 2

Do it like this:

:id="'collape' + thread_ref"

Anything inside the " " when you bind a property using v-bind or : is javascript. So you can do any single line expressions that you do in JavaScript

Share:
16,198
Brad
Author by

Brad

Updated on June 07, 2022

Comments

  • Brad
    Brad almost 2 years

    I'm trying to combine a string and a prop to create a unique id for a bootstrap accordion.

    I want to combine "collapse" and {{ thread_ref }} to create something like: id="collapse_321"

    Vue gives me an error when I try to do this and says to use v-bind.

    I have tried that but that only accepts a string of the name of the prop/data, how can I combine a string and data?

  • Brad
    Brad over 6 years
    Thank you so much, it seems so obvious now that you have pointed it out, I feel dumb :P