straysheep3
10/21/2018 - 1:00 PM

電話番号コンポーネント

使用ライブラリ cleave.js

親コンポーネントで、optionsを指定する(inputのタイプ、phoneなら国も)

<template>
  <input ref="input" type="text">
</template>

<script>
import Creave from "cleave.js";
import CleavePhone from 'cleave.js/dist/addons/cleave-phone.jp';

export default {
  name: "ZipForm",
  props: {
    value: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      default: () => ({})
    },
    events: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      cleave: null
    }
  },
  methods: {
    emitEvent () {
      this.$emit('input', this.$el.value)
    }
  },
  mounted () {
    this.$el.value = this.value
    this.cleave = new Cleave(this.$el, this.options)
    Object.keys(this.events).map((key) => {
      this.$refs.input.addEventListener(key, this.events[key])
    })
    if (this.options.maxLength) {
      this.$el.setAttribute('maxlength', this.options.maxLength)
    }
    // in case of cleave.js remove result or properties from cleave instance.
    if (this.cleave.properties && this.cleave.properties.hasOwnProperty('result')) {
      this.$watch('cleave.properties.result', this.emitEvent)
    } else {
      this.$el.addEventListener('input', this.emitEvent)
    }
  },
  beforeDestroy () {
    this.cleave.destroy()
  },
  watch: {
    options: {
      deep: true,
      handler (val) {
        this.cleave.destroy()
        this.cleave = new Cleave(this.$el, val)
      }
    }
  },
}
</script>

<style>
input {
  border: 1px solid black;
}
</style>

<template>
  <ZipForm :options="{ phone: true, phoneRegionCode: 'jp'}"></ZipForm>
</template>

<script>
import ZipForm from "../components/ZipForm";
export default {
  components: {
    ZipForm
  }
}
</script>