0
1

More than 1 year has passed since last update.

住所自動取得(郵便番号全角入力対応)[Vus.js2]

Last updated at Posted at 2022-12-31

環境

バージョン
Vue.js 2.7.14
axios-jsonp 1.0.4

使用API

郵便番号-住所検索API
https://zipaddress.net/

レスポンス内容

キー バリュー
pref 都道府県名
city 市区町村名
town 町域名
address cityとtownを結合したもの
fullAddress 都道府県+市区町村+町域名

全角→半角を変換用の関数を用意

//全角英数記号を半角に変換する
const replaceToHalfWidth = strVal => {
  var halfVal = String(strVal).replace(/[!-~]/g, function (str) {
    return String.fromCharCode(str.charCodeAt(0) - 0xFEE0);
  });

  // 文字コードシフトで対応できない文字の変換
  return halfVal.replace(/”/g, "\"")
    .replace(/’/g, "'")
    .replace(/‘/g, "`")
    .replace(/¥/g, "\\")
    .replace(/ /g, " ")
    .replace(/〜/g, "~")
}

vueファイル(シングルファイルコンポーネント)

<template>
  <div>
    郵便番号<input type="text" v-model="post_code" @change="getAddressFromAPi">
    都道府県<input type="text" v-model="pref">
    住所<input type="text" v-model="address">
  </div>
</template>
<script>
import jsonpAdapter from 'axios-jsonp'

export default {
  data () {
    return {
      post_code: null,
      pref: null,
      address: null,
    }
  },
  methods: {
    getAddressFromAPi() {
      const replacedAddress = replaceToHalfWidth(this.post_code)

      axios.get(`https://api.zipaddress.net/?zipcode=${replacedAddress}`,
        {adapter: jsonpAdapter})
        .then(res => {
          this.pref = res.data.pref
          this.address = res.data.address
            })
        }
  },
}
</script>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1