axiosでHttp GET
Home.vue
<template> <!-- ルートエレメントが1個必要 !!! --> <div> <button @click = 'clicked'>"GET"</button> <hr> <p class="cmn">{{ resp_data }}</p> </div> </template> <script lang="ts"> import { Component, Watch, Vue } from 'vue-property-decorator'; import axios from "axios"; @Component({ components: { }, }) export default class Home extends Vue { public resp_data?: string = "no data."; private http; public created(){ console.log("[created]") this.http = axios.create(); } public clicked(){ console.log("[clicked]") this.get_fb().then(); } public async get_fb() { const res = await this.http.get("https://xxxxxxxx.firebaseio.com/person.json"); console.log(res.data); this.resp_data = res.data; return res; } } </script> <style> .cmn { margin: 10px; } </style>
APIをComponentで分けた場合(APIボタンモジュール)
Pages/New.vue
<template> <!-- ルートエレメントが1個必要 !!! --> <div> <API class="cmn" @emit_clicked='cb_clicked' caption="API"></API> <hr> <p class="cmn">RESPONSE</p> <p class="cmn">{{ resp_data }}</p> </div> </template> <script lang="ts"> import { Component, Watch, Vue } from 'vue-property-decorator'; import API from "@/components/API.vue"; @Component({ components: { API, }, }) export default class New extends Vue { private resp_data?:string=""; public cb_clicked(s:string){ console.log("[cb_clicked]") console.log(s); this.resp_data=s; } } </script> <style> .cmn { margin: 10px; } </style>
API.vue
<template> <button @click="onClick">{{caption}}</button> </template> <script lang="ts"> import {Component, Prop, Emit, Vue} from "vue-property-decorator" import axios from "axios"; @Component export default class API extends Vue { private http; public resp_data?: string = "no data."; @Prop() public caption?: string; // 上位にイベント通知 @Emit() public emit_clicked(string){ } public created(){ console.log("[API]created()") this.http = axios.create(); } public onClick(){ this.get_person(); } public async get_person() { console.log("[API]get_fb()") const res = await this.http.get("https://xxxxxxxx.firebaseio.com/person.json"); console.log(res.data); this.resp_data = res.data; this.emit_clicked(res.data); return res; } } </script>