您当前的位置: 首页 > 

62Vue - 自定义事件(使用自定义事件的表单输入组件)

杨林伟 发布时间:2019-07-29 11:21:49 ,浏览量:1

自定义事件也可以用来创建自定义的表单输入组件,使用 v-model来进行数据双向绑定。牢记:


仅仅是一个语法糖:


所以在组件中使用时,它相当于下面的简写:


所以要让组件的 v-model 生效,它必须:

  • 接受一个 value 属性
  • 在有新的 value 时触发 input 事件

一个非常简单的货币输入: HTML代码:


JS代码:

Vue.component('currency-input', {
  template: '\
    \
      $\
      \
    \
  ',
  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))
    }
  }
})

在这里插入图片描述

关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 1浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.2028s