在Vue.js中使用组件的双向绑定

时间:2017-05-27 07:11:23

标签: vue.js vuejs2

我是Vue.js的新学员,并尝试在官方指南中实施示例(example of currency filter)。

但是,在实现时,我将组件(value)的属性重命名为(priceValue)。更改后,输入框无法格式化值 - 它始终显示“0”而不是格式化值。

这是我做的唯一改变。有什么问题?

Vue.component('currency-input', {
  template: '\
    <div>\
      <label v-if="label">{{ label }}</label>\
      $\
      <input\
        ref="input"\
        v-bind:value="priceValue"\
        v-on:input="updateValue($event.target.value)"\
        v-on:focus="selectAll"\
        v-on:blur="formatValue"\
      >\
    </div>\
  ',
  props: {
    priceValue: {
      type: Number,
      default: 0
    },
    label: {
      type: String,
      default: ''
    }
  },
  mounted: function () {
    this.formatValue()
  },
  methods: {
    updateValue: function (value) {
      var result = currencyValidator.parse(value, this.priceValue)
      if (result.warning) {
        this.$refs.input.value = result.value
      }
      this.$emit('input', result.value)
    },
    formatValue: function () {
      // console log here always get 0 
      this.$refs.input.value = currencyValidator.format(this.priceValue)
    },
    selectAll: function (event) {
      setTimeout(function () {
      	event.target.select()
      }, 0)
    }
  }
})

new Vue({
  el: '#app',
  data: {
    price: 0,
    shipping: 0,
    handling: 0,
    discount: 0
  },
  computed: {
    total: function () {
      return ((
        this.price * 100 + 
        this.shipping * 100 + 
        this.handling * 100 - 
        this.discount * 100
      ) / 100).toFixed(2)
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/chrisvfritz/5f0a639590d6e648933416f90ba7ae4e/raw/98739fb8ac6779cb2da11aaa9ab6032e52f3be00/currency-validator.js"></script>

<div id="app">
  <currency-input 
    label="Price" 
    v-model="price"
  ></currency-input>
  <currency-input 
    label="Shipping" 
    v-model="shipping"
  ></currency-input>
  <currency-input 
    label="Handling" 
    v-model="handling"
  ></currency-input>
  <currency-input 
    label="Discount" 
    v-model="discount"
  ></currency-input>
  
  <p>Total: ${{ total }}</p>
</div>

1 个答案:

答案 0 :(得分:0)

根据DOCS

  

对于使用v-model的组件,它应该是(这些可以是   在2.2.0 +中配置:

     
      
  • 接受value道具
  •   
  • 使用新值
  • 发出input事件   

可以使用model选项块配置 sinse 2.2.x:

Vue.component('currency-input', {
  model: {
    prop: 'propValue',
    // event: 'input'  - you can also customize event name, not needed in your case
  },

有了这个,您的代码将再次运行:https://jsfiddle.net/wostex/j3a616a5/