序章

Vue.js は、ユーザーインターフェイスを構築するためのフロントエンドJavaScriptフレームワークです。 段階的に採用できるようにゼロから設計されており、他のライブラリや既存のプロジェクトとうまく統合できます。 This approach makes it a good fit for small projects as well as sophisticated single-page applications when used with other tooling and libraries.

API、またはアプリケーションプログラミングインターフェイスは、2つのアプリケーションが相互に通信できるようにするソフトウェア仲介者です。 APIは、データベースやプログラミング言語の違いを気にすることなく、他の開発者が自分のアプリで消費できるデータを公開することがよくあります。 開発者は、JSON形式でデータを返すAPIからデータを頻繁にフェッチし、フロントエンドアプリケーションに統合します。 Vue.jsは、これらの種類のAPIを使用するのに最適です。

In this tutorial, you’ll create a Vue application that uses the Cryptocompare API to display the current prices of two leading cryptocurrencies: Bitcoin and Ethereum. Vueに加えて、 Axiosライブラリを使用してAPIリクエストを作成し、取得した結果を処理します。 Axios is a great fit because it automatically transforms JSON data into JavaScript objects, and it supports Promises, leading to code that’s easier to read and debug. そして、見栄えを良くするために、 FoundationCSSフレームワークを使用します。

:Cryptocompare APIは、非営利目的でのみライセンスされています。 商用プロジェクトで使用する場合は、ライセンス条項を参照してください。

前提条件

Before you begin this tutorial, you’ll need the following:

  • Atom Visual Studio Code SublimeTextなどのJavaScript構文の強調表示をサポートするテキストエディター。 これらのエディターは、Windows、macOS、およびLinuxで使用できます。
  • HTMLとJavaScriptを一緒に使用することに精通していること。 詳細については、JavaScriptをHTMLに追加する方法をご覧ください。
  • JavaScriptでJSONを操作する方法で詳細を学ぶことができる、JSONデータ形式に精通していること。
  • APIへのリクエストの作成に精通していること。 APIの操作に関する包括的なチュートリアルについては、Python3でWebAPIを使用する方法を参照してください。 Python用に書かれていますが、APIを使用するためのコアコンセプトを理解するのに役立ちます。

ステップ1—基本的なVueアプリケーションを作成する

In this step, you’ll create a basic Vue application. モックアップされたデータを使用して単一のHTMLページを作成し、最終的にAPIからのライブデータに置き換えます。 Vue.jsを使用して、このモックされたデータを表示します。 この最初のステップでは、すべてのコードを1つのファイルに保存します。

と呼ばれる新しいファイルを作成します index.html テキストエディタを使用します。

In this file, add the following HTML markup, which defines an HTML skeleton and pulls in the Foundation CSS framework and the Vue.js library from content delivery networks (CDNs). By using a CDN, there’s no additional code you need to download to start building your app.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
  <meta charset="utf-8">
  <title>Cryptocurrency Pricing Application</title>
</head>

  <body>
    <div class="container" id="app">
      <h3 class="text-center">Cryptocurrency Pricing</h3>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in USD  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinUSD }}</p>
          </div>
        </div>
      </div>
    </div>

    <script src="https://unpkg.com/vue@3"></script>
  </body>
</html>

この線 {{ BTCinUSD }} is a placeholder for the data that Vue.js will provide, which is how Vue lets us declaratively render data in the UI. そのデータを定義しましょう。

真下 <script> tag with Vue, add this code to create a new Vue application and define a data structure for display on the page:

index.html
...
   <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return {
              BTCinUSD: 3759.91
            }
          }  
        }).mount('#app')
    </script>
...

このコードは、新しいVueアプリインスタンスを作成し、そのインスタンスを要素にアタッチします。 idapp. Vueは、このプロセスをマウントアプリケーションと呼んでいます。 新しいVueインスタンスを定義し、構成objectを渡して構成します。 To the createApp instance, we pass a data object that returns the value of BTCinUSD. Further, we have invoked the mount method of the createApp instance with argument #app that specifies the id of the element we want to mount this application on and a data option containing the data we want available to the view.

この例では、データモデルに、ビットコインの価格のモック値を保持する単一のキーと値のペアが含まれています。 { BTCinUSD: 3759.91}. このデータは、次のようにキーを二重中括弧で囲んだ場所のHTMLページまたはビューに表示されます。

index.html
<div class="card-divider">
  <p>{{ BTCinUSD }}</p>
</div>

最終的に、このハードコードされた値をAPIからのライブデータに置き換えます。

このファイルをブラウザで開きます。 画面に次の出力が表示され、模擬データが表示されます。

米国での価格を表示しています ドル。 ユーロなどの追加の通貨で表示するには、データモデルに別のキーと値のペアを追加し、マークアップに別の列を追加します。 First, add the line for Euros to the data model:

index.html
  <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return { 
              BTCinUSD: 3759.91, 
              BTCinEURO: 3166.21
            }
          }  
        }).mount('#app')
    </script>

Then replace the existing <div class> section with the following lines.

index.html
  <div class="container" id="app">
      <h3 class="text-center">Cryptocurrency Pricing</h3>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in USD  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinUSD }}</p>
          </div>
        </div>
      </div>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in EURO  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinEURO }}</p>
          </div>
        </div>
      </div>
    </div>

次に、ファイルを保存してブラウザにリロードします。 アプリは、ビットコインの価格をユーロと米ドルの両方で表示するようになりました。

In this step, you created your Vue app with some sample data to ensure it loads. We’ve done all the work in a single file so far, so now we’ll split things into separate files to improve maintainability.

ステップ2—明確にするためにJavaScriptとHTMLを分離する

物事がどのように機能するかを学ぶために、すべてのコードを1つのファイルに配置しました。 In this step, you’ll separate the application code into two separate files: index.htmlvueApp.js. The index.html file will handle the markup, and the JavaScript file will contain the application logic. 両方のファイルを同じディレクトリに保存します。

まず、 index.html ファイルを作成してJavaScriptコードを削除し、 vueApp.js ファイル。

ファイルの次のセクションを見つけます。

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return {
              BTCinUSD: 3759.91,
              BTCinEURO: 3166.21
            }
          }             
        }).mount('#app')
    </script>
...

そして、次のように変更します。

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script src="vueApp.js"></script>
...

次に、を作成します vueApp.js と同じディレクトリにあるファイル index.html ファイル。

この新しいファイルに、元々あったものと同じJavaScriptコードを配置します。 index.html ファイル、なし <script> タグ:

vueApp.js
 const { createApp } = Vue
        
createApp({    
  data() {
    return {
      BTCinUSD: 3759.91,
      BTCinEURO: 3166.21
    }
  }  
}).mount('#app')

ファイルを保存してリロードします index.html ブラウザで。 以前に見たのと同じ結果が表示されます。

Here, you separated the app from the markup. Next, you’ll add more data to support more cryptocurrencies than just Bitcoin.

ステップ3—Vueを使用してデータを反復処理する

In this step, you’ll restructure the data and modify the view to show prices for both Bitcoin and Ethereum.

を開きます vueApp.js file and modify the return portion of the data model so it looks like this:

vueApp.js
const { createApp } = Vue
      
createApp({
  data() {
    return { 
        results: {"BTC": {"USD":3759.91,"EUR":3166.21}, "ETH": {"USD":281.7,"EUR":236.25}}
    }
  }
}).mount('#app')

私たちのデータモデルは、ネストされたデータ構造でもう少し複雑になっています。 これで、というキーができました results which contains two records: one for Bitcoin prices and another for Ethereum prices. This new structure will let us reduce some duplication in our view. It also resembles the data we’ll get from the Cryptocompare API.

Save the file.

次に、マークアップを変更して、よりプログラム的な方法でデータを処理しましょう。

を開きます index.html ファイルを作成し、ビットコインの価格を表示するファイルのこのセクションを見つけます。

index.html
...
    <div class="columns medium-4" >
      <div class="card">
        <div class="card-section">
          <p> BTC in USD  </p>
        </div>
        <div class="card-divider">
          {{BTCinUSD}}
        </div>
      </div>
    </div>

    <div class="columns medium-4" >
      <div class="card">
        <div class="card-section">
          <p> BTC in EURO  </p>
        </div>
        <div class="card-divider">
          {{BTCinEURO}}
        </div>
      </div>
    </div>

  </div>
...

定義したデータセットを反復処理するこのコードに置き換えます。

index.html
...
  <div class="columns medium-4" v-for="(result, index) in results">
    <div class="card">
      <div class="card-section">
        <p> {{ index }} </p>
      </div>
      <div class="card-divider">
        <p>$ {{ result.USD }}</p>
      </div>
      <div class="card-section">
        <p> &#8364 {{ result.EUR }}</p>
      </div>
    </div>
  </div>
...

This code uses the v-for directive which acts like a for-loop. データモデル内のすべてのキーと値のペアを繰り返し処理し、それぞれのデータを表示します。

When you reload in the browser, you’ll see the mocked prices:

この変更により、新しい通貨をに追加できます results のデータ vueApp.js and have it display on the page without futher changes.

Add another mocked entry to the dataset with the highlighted information to try this out:

vueApp.js
const { createApp } = Vue
      
createApp({
  data() {
    return {
        results: {"BTC": {"USD":3759.91,"EUR":3166.21}, 
        "ETH": {"USD":281.7,"EUR":236.25},
        "NEW Currency":{"USD":5.60,"EUR":4.70}}
    }
  }
}).mount('#app')

Include the trailing comma after the Ethereum entry. Save the file.

ここでWebブラウザにページをロードすると、新しいエントリが表示されます。

プログラムでデータに取り組むと、マークアップに手動で新しい列を追加する必要はありません。

Here, you used sample data to view pricing for multiple currencies. Now let’s fetch real data using the Cryptocompare API.

ステップ4—APIからデータを取得する

In this step, you will replace the mocked-up data with live data from the Cryptocompare API to show the price of Bitcoin and Ethereum on the webpage in US Dollars and Euros.

To get the data for our page, we’ll make a request to https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR, which requests Bitcoin and Ethereum in US Dollars and Euros. This API will return a JSON response.

使用する curl to make a request to the API to see the response in a terminal session:

  1. curl 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR'

次のような出力が表示されます。

Output
{"BTC":{"USD":21694.18,"EUR":21407.64},"ETH":{"USD":1504.02,"EUR":1485.99}}

This result looks like the hard-coded data model you used in the previous step, but with the current values of the Bitcoin and Ethereum. ここで行う必要があるのは、アプリからこのURLにリクエストを送信してデータを切り替えることだけです。

リクエストを行うには、Vueの Mounted()関数を GET データをフェッチしてに保存するAxiosライブラリの機能 results データモデルの配列。 The mounted Vueアプリが要素にマウントされると、関数が呼び出されます。 Vueアプリがマウントされたら、APIにリクエストを送信し、結果を保存します。 Webページに変更が通知され、値がページに表示されます。

まず、開く index.html Vueをインクルードした行の下にスクリプトを追加して、Axiosライブラリをロードします。

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="vueApp.js"></script>
...

ファイルを保存して開きます vueApp.js.

Modify and update vueApp.js so it makes a request to the API and fills the data model with the results.

vueApp.js
const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR";
const { createApp } = Vue
      
createApp({    
  data() {
    return {
        results:[]
    }
},
    mounted() {
        axios.get(url).then(response => {
            this.results = response.data
        })
  }
}).mount('#app')

のデフォルト値を削除したことに注意してください results 空の配列に置き換えました。 We won’t have data when our app first loads, but the HTML view is expecting some data to iterate over when it loads.

The axios.get 関数はPromiseを使用します。 APIがデータを正常に返すと、 then ブロックが実行され、データが results 変数。

ファイルを保存してリロードします index.html Webブラウザのページ。 This time, you’ll see the current prices of the cryptocurrencies.

If you don’t see anything, you can review How To Use the JavaScript Developer Console and use the JavaScript console to debug your code. The page may take a minute to refresh with data from the API.

You can also view this Github repository, which contains the htmljs files that you can download for cross-confirmation. You can also clone the repository.

In this step, you modified your app to call live data for review.

結論

50行未満で、Vue.js、Axios、およびCryptocompareAPIの3つのツールのみを使用してAPIを消費するアプリケーションを作成しました。 ページにデータを表示する方法、結果を反復処理する方法、静的データをAPIからの結果に置き換える方法を学びました。

基本を理解したので、アプリケーションに他の機能を追加できます。 このアプリケーションを変更して追加の通貨を表示するか、このチュートリアルで学習した手法を使用して、別のAPIを使用して別のWebアプリケーションを作成します。