Vue 中值绑定中的字符串连接

Pro*_*mer 6 vue.js vue-component vuejs2

我刚刚开始学习Vue,所以这可能是一个愚蠢的问题。我创建了一个 Vue 组件,想要在值绑定中进行字符串连接。

像这样。

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

但这似乎是错误的语法。任何人都可以帮助我如何实现这一目标。

在示例中,还有另一种方法可以做到这一点,例如:

template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
Run Code Online (Sandbox Code Playgroud)

但是使用值绑定可以实现吗?

ski*_*tle 6

正如另一个答案中已经指出的那样,您可以使用计算属性来完全删除表达式,但这并不是让您的代码正常工作所必需的。如果您一直使用单个文件组件,那么您的模板将会正常工作。这里的“错误语法”是由于模板使用双引号字符串文字导致的,导致嵌套双引号。

双引号需要用斜杠转义。这与 Vue 无关,它是原始 JavaScript:

template:"<input type='button' v-on:click='count++' v-bind:value='\"Total Counter :\"+count'/>"
Run Code Online (Sandbox Code Playgroud)

虽然不正确,但我也建议缩写为v-on:clickto@clickv-bind:valueto :value

template: "<input type='button' @click='count++' :value='\"Total Counter :\" + count'/>"
Run Code Online (Sandbox Code Playgroud)


Aus*_*tio 3

我会用计算属性来做到这一点。我也可能会将其从输入类型交换为按钮,但以下是如何使用当前输入解决问题。

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'/>"
}))
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2"></script>
<html>
<div id="app"/>
Run Code Online (Sandbox Code Playgroud)