vue 基础教程疑问

<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: {
    // Instead of updating the value directly, this
    // method is used to format and place constraints
    // on the input's value
    updateValue: function (value) {
      var formattedValue = value
        // Remove whitespace on either side
        .trim()
        // Shorten to 2 decimal places
        .slice(0, value.indexOf('.') + 3)
      // If the value was not already normalized,
      // manually override it to conform
      if (formattedValue !== value) {
        this.$refs.input.value = formattedValue
      }
      // Emit the number value through the input event
      this.$emit('input', Number(formattedValue))
    }
  }
})

v-on:input="updateValue($event.target.value)" 这个是说,如果发生了input事件,调用updateValue方法,但是方法内部再去this.$emit干嘛。这不是又触发了次input事件吗?然后一直循环下去?

还有,父子组件怎么区分,我看示例也只注册了一个组件呀?

阅读 3k
3 个回答

this.$emit()触发的input事件不是组件内部<input>元素的input事件,而是组件根元素<currency-input>的input事件,v-model是一个语法糖,你把

<currency-input v-model="price"></currency-input>`

还原为

<currency-input v-bind:value="price" v-on:input="setValue"></currency-input>    
methods: {
    setValue(value) {
        this.price = value
    }
}

就知道了,其实它触发的这上面的input事件,实际执行的是setValue方法

新手上路,请多包涵

这个例子,好像有问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题