javascript - Vue custom control v-model two-way binding
为情所困
为情所困 2017-07-05 11:01:51
0
1
780
<currency-input v-model="price"></currency-input>

Vue.component('currency-input', {
  template: '\
    <span>\
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
      >\
    </span>\
  ',
  props: ['value'],
  methods: {
    // 不是直接更新值,而是使用此方法来对输入值进行格式化和位数限制
    updateValue: function (value) {
      var formattedValue = value
        // 删除两侧的空格符
        .trim()
        // 保留 2 小数位
        .slice(0, value.indexOf('.') + 3)
      // 如果值不统一,手动覆盖以保持一致
      if (formattedValue !== value) {
        this.$refs.input.value = formattedValue
      }
      // 通过 input 事件发出数值
      this.$emit('input', Number(formattedValue))
    }
  }
})

vue入门指导里的,请问input事件是什么时候触发的,一旦触发,`this.$emit('input', Number(formattedValue))`不会导致input事件不停被触发,updateValue循环被调用吗?
为情所困
为情所困

reply all(1)
世界只因有你

The oninput event is an event supported by most browsers except IE. It is triggered when the value changes, in real time, that is, it will be triggered every time a character is added or deleted. However, when the value is changed through js, it will not be triggered;

So input is triggered when the content in input changes. As for this.$emit('input', Number(formattedValue)), in fact, the custom event 'input' is sent here. He uses It is for the communication between parent and child components, which means that the emit event here will not be captured by the component itself, that is, it will not trigger the updateValue here. Your <currency-input v-model= "price"></currency-input>Add the monitoring of input here, emit is triggered here, so the loop call you mentioned will not be sent.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!