LoginSignup
1
0

More than 1 year has passed since last update.

Nuxt.jsとYubinBangoを組み合わせて使う

Last updated at Posted at 2021-06-29

郵便番号からの住所検索をいい感じに実装したくて調べたが、どれもこれも帯に短し襷に長しのよう。
自分の要件にFitしそうな↓をベースにしました。
- https://ryus.dev/articles/2020-12-01-auto-zipcode

まずはscriptタグでyubinbango-core.jsを読み込み。

nuxt.config.js
  head: {
    script: [
      {
        src: "https://yubinbango.github.io/yubinbango-core/yubinbango-core.js",
      },
    ],
  },

ロジックはpluginsに置くことにする。Promiseでいい感じにしておく。

plugins/yubinbango.js
import Vue from "vue";

const yubinbango= function (zipCode) {
  return new Promise(
    (resolve) => new YubinBango.Core(zipCode, (address) => resolve(address))
  );
};

Vue.prototype.$yubinbango= yubinbango;

で、書いたコードをpluginsに追加。

nuxt.config.js
  plugins: [
    { src: "~/plugins/yubinbango.js" },
  ],

動く。

sample.vue
<template>
  <label>郵便番号<input v-model="zipCode" type="input" /></label>
  <label>住所<input v-model="address" type="input" /></label>
</template>

<script>
export default {
  data: () => ({
    zipCode: "",
    address: "",
  }),

  watch: {
    zipCode(zipCode) {
      this.$yubinbango(zipCode).then(
        (addr) => (this.address = addr.locality + addr.street)
      );
    },
  },
};
</script>


1
0
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
1
0