0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue.js3系 郵便番号を入力すると自動で住所入力する機能

Last updated at Posted at 2022-12-18

はじめに

Vue.js3で郵便番号を入力すると自動で住所入力する機能を使用したいと思い備忘録もかねて記事を書こうと思います。

結論

下記のライブラリをインストールすると使用可能です。

$ npm i yubinbangou-core2@^0.6.3

インストール後、package.jsonの中にyubinbangou-core2がインストールされている事を確認

package.json
"dependencies": {
    "yubinbango-core2": "^0.6.3"
}

Vueファイルに記述

インストールしたライブラリを使用するためにyubinbangou-core2をインポートする

pages/index.vue
<script setup>
import { Core as YubinbangoCore } from '@yubinbango-core2';
</script>                       

存在する郵便番号を入力しconsole.logで表示されるか確認

YubinbangoCoreを使うためにはnewを使ってインスタンスを作成する必要があります。
(postcodeを文字列として扱っている理由は、int型で実行するとエラーになるためです。原因は分からないです。。。)

第二引数はコールバック関数になっておりvalueに住所が返ってきます。
ちなみに、@changeは入力フォームから離れるとイベントが発生します。
console.logで確認します。

pages/index.vue
<script setup>
import { reactive } from 'vue'
import { Core as YubinbangoCore } from '@yubinbango-core2';

const form = reactive({
    postcode: null
})

const fetchAddress = () => {
    new YubinbangoCore(String(form.postcode), (value) => {
        console.log(value)
    })
}
</script>

<template>
<input type="number" name="postcode" @change="fetchAddress" v-model=form.postcode>
</template>

確認するとこのように返ってきます。
value.キーの値で値が取得できます。

console.log
{
    extended: ""
    locality: "新宿区"
    region: "東京都"
    region_id: 13
    street: "四谷坂町"
}

まとめ

郵便番号のinputタグに郵便番号を入力
入力後、カーソルを離すとfetchAddressが実行される
addressタグでは、v-modelを使用していますのでreactive対応しているaddressの値が変われば、住所に値が入る仕組みになっています。

pages/index.vue
<script setup>
import { reactive } from 'vue'
import { Core as YubinbangoCore } from 'yubinbango-core2';

const form = reactive({
    postcode: null,
    address: null
})

const fetchAddress = () => {
    new YubinbangoCore(String(form.postcode), (value) => {
        //console.log(value)
        form.address = value.region + value.locality + value.street
    })
}
</script>

<template>
<label>郵便番号</label><br>
<input type="number" name="postcode" @change="fetchAddress" v-model=form.postcode><br>
<label>住所</label><br>
<input type="text" name="address"  v-model=form.address><br>
</template>
0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?