パターン
usePostalCode Composable
yubinbango-core2 を Nuxt 3 の Composable に包んだパターン。 composables/usePostalCode.ts に分離することで、 複数のフォームページから同じロジックを再利用できます。
実装コード
composables/usePostalCode.ts
import YubinBango from 'yubinbango-core2' // core2 を composable で利用
export function usePostalCode() {
const loading = ref(false)
const error = ref<string | null>(null)
function lookup(zipcode: string): Promise<PostalAddress | null> {
const clean = zipcode.replace(/-/g, '')
if (!/^\d{7}$/.test(clean)) return Promise.resolve(null)
loading.value = true
return new Promise((resolve) => {
new YubinBango.Core(clean, (addr) => {
loading.value = false
resolve(addr.region
? { pref: addr.region, city: addr.locality, street: addr.street }
: null
)
})
})
}
function watchAndFill(zipRef, target) {
watch(zipRef, async (val) => {
const result = await lookup(val)
if (result) {
target.pref = result.pref
target.city = result.city
target.address = result.street
}
})
}
return { lookup, watchAndFill, loading, error }
}pages/composable.vue (利用側)
const { watchAndFill, loading: postalLoading, error: postalError } = usePostalCode()
const form = reactive({ zip: '', pref: '', city: '', address: '' })
// ← これだけでフォームへの自動入力が完成
watchAndFill(toRef(form, 'zip'), form)- ✅ ページコンポーネントが非常にシンプルになる
- ✅ 複数フォームページで同じロジックを再利用できる
- ✅ loading / error 状態も composable に集約
- ✅ バックエンド(yubinbango-core2 / zipcloud)を差し替えやすい
- ℹ️ このページの composable 実装は `yubinbango-core2` を使用
core と core2 の違い(Composable 観点)
・`yubinbango-core`: 元パッケージ(このページでは直接利用しない)
・`yubinbango-core2`: `module.exports` 追加フォーク(このページの composable 実装で使用)