LoginSignup
0
0

More than 1 year has passed since last update.

Vue2でextendsオプションを使ってaxiosの共通処理を作成した話

Last updated at Posted at 2022-04-05

概要

どのVueでも使うような共通処理を1つのコンポーネントとして定義して、実際のVueでそれを継承したような形で実装したかったのだが、いろんな書き方が出てきて頭痛くなったのでここに完結にまとめる。

調べて出てきたもの

「vue extends」と検索すると大量の情報がヒットする

  • Vue.extend()の話
    これが一番出てくる....ただ、これはVueの定義をする部分の書き方に関するものっぽくて継承とかの話とは微妙に違うんですよね..(関係無いわけでは無いんですけど)
  • typescriptの話
    次によく出てくる話。別に今回は書き換えたいわけじゃないんだよなぁ...
  • クラスコンポーネントの話
    export default class A extends B {}
    みたいなやつ
    継承ではあるんだけど、typescript考慮の話に近いみたいで、やりたいこととは違う
  • Vueのextendsオプション
    これが知りたかったこと

やりたいこと

共通で使える親Vueを定義して、それぞれのcomponentでそちらをextendsして、メソッド等を継承しただけで使えるようにする。
axiosを用いた処理の共通化など

実装

共通処理を記載したVueファイル

BaseApp.vue
<script>
import Vue from 'vue'
import axios from 'axios'
export default {
  data() {
    return {
      hugahuga: 'フガフガ',
    };
  },  
  methods: {
    async getRequest(url){
      const promise = await axios
        .get(url)
      return promise
    },
    hogehoge(){
      console.log(this.hugahuga)
    }
  }
}
</script>

継承したVueを使うファイル

HelloWorld.vue
<script>
import Vue from 'vue'
import BaseApp from './BaseApp.vue'

export default {
  extends: BaseApp,
  props: {
    msg: {
        type: String,
        default: ""
      }
  },
  created() {
    this.hogehoge()
    this.get()
  },
  methods: {
    async get(){
      const response = await this.getRequest('https://api.coindesk.com/v1/bpi/currentprice.json')
      console.log(response)
    }
  }
}

</script>

これで済む話だったのにだいぶ遠回りをしました...

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