Vue.jsの基礎勉強3-computedの理解とaxiosを用いたAPIを使う方法-
はじめに
今回はcomputed
とmethods
の違いについてとaxiosを用いたAPIの利用をQiitaのAPIを用いて勉強した。
算出プロパティ
- 全体像
See the Pen 算出プロパティ by KKZoo (@kkzoo) on CodePen.
算出プロパティの主な特徴
算出プロパティを用いることで複数回使用する場合の複雑な処理をスッキリ書くことができる。
~略~ <p> {{ message.split("").reverse().join("") }} </p> <p> {{ reversedMessege }} </p> <p> {{ reversedMessegeMethod() }} </p>
~略~ computed: { reversedMessege: function(){ return this.message.split("").reverse().join("") }, ~略~ methods: { reversedMessegeMethod: function(){ return this.message.split("").reverse().join("") },
methodsとcomputedの違いについて
キャッシュについての実験の出力をみてもらうと分かるのだが、methods
は関数なので呼び出されるたびに計算をして出力を行うが、computed
の方は計算を1度だけしてその値を使い回している。よって次のことが言える。
methods
の場合は計算結果をキャッシュしないcomputed
の場合は計算結果をキャッシュしている
axiosを用いてQiitaのAPIを利用した
axiosを用いることでAPiを叩くことができる。基本的な構文は以下になる。
// Make a request for a user with a given ID axios.get('/user', {params: { ID: 1234, name: testname }}) .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });
See the Pen axios by KKZoo (@kkzoo) on CodePen.
終わりに
QiitaのAPIを取得するページを作成するのが楽しかった。