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?
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'/>"
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'/>"
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With