概要
Vueのインスタントプロパティを使ってaxiosのインスタンスを作成しコンポーネントからaxiosを使えるようにする
axiosはPromiseで HTPPリクエストをbrowser,nodeで実行できるライブラリ.
axiosではhttpのインスタンスを作成することによって共通の baseURL
や header
を設定できる
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Vueのインスタントプロパティは どのComponentからでもアクセスできる処理やデータを追加できる仕組み.
Vue routerを入れると$router
が, Vuexを入れると $store
が追加される.
Vueアプリ上でAPIを叩くたびにhttp://....
と設定するのが面倒なのでaxiosのインスタンスを使用して事前に設定する.
環境
vue-cliで作成したプロジェクトと仮定する.
typescript ,vuex,router,pwa を設定
コード
src/main.ts
でaxiosインスタンスを作成,baseURLを設定
const http = axios.create({baseURL: 'https://some-domain.com/}); Vue.prototype.$http = http;
<template>... </template> <script lang="ts"> ... @Component export default class Home extends Vue { public makeRoom() { const ownerAuth = "/owner/auth"; this.$http.get(ownerAuth, {params: {id: password}}).then(value => { // console.log("%o", value.data); if (value.data === "OK") { this.dialog = false; this.$router.push({path: "/makeRoom"}); } else { this.dialog = false; } }).catch(reason => { this.dialog = false; }); } } }
baseURLを省けるので見やすくなる.