Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation in value bind in Vue

I have just started learning Vue, so it might be silly question. I have created a Vue component and want to do string concatenation in value bind.

Like this.

Vue.component('button-counter',{
    data:function(){
        return { count : 0}
    },
    template:"<input type='button' v-on:click='count++' v-bind:value='"Total Counter :"+count'/>"
})

But it's seems to be wrong syntax. Can anyone please help me on how I can achieve this.

In example there is another way of doing this, e.g:

template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

But is it possible to achieve using value binding?

like image 555
Programmer Avatar asked Sep 22 '18 04:09

Programmer


2 Answers

As has already been noted in another answer you could use a computed property to remove the expression entirely but that is not required to get your code to work. If you had been using a single file component then your template would have worked fine. The 'wrong syntax' here is a consequence of using a double-quoted string literal for your template, leading to nested double quotes.

The double quotes need escaping with slashes. This is nothing to do with Vue, it's raw JavaScript:

template:"<input type='button' v-on:click='count++' v-bind:value='\"Total Counter :\"+count'/>"

While not incorrect, I would also suggest abbreviating v-on:click to @click and v-bind:value to :value.

template: "<input type='button' @click='count++' :value='\"Total Counter :\" + count'/>"
like image 54
skirtle Avatar answered Oct 19 '22 04:10

skirtle


I would do this with a computed property. I would also probably swap this up from an input type to a button, but here is how to solve with current input.

new Vue(({
  el: "#app",
  data:function(){
    return { count : 0}
  },
  computed: {
    buttonText() {
      return "Total Counter : " + this.count; 
    }
  }, 
  template:"<input type='button' v-on:click='count++' v-bind:value='buttonText'/>"
}))
like image 3
Austio Avatar answered Oct 19 '22 05:10

Austio