LoginSignup
12
11

More than 3 years have passed since last update.

Vue.jsでテーブルを動的に行追加する

Last updated at Posted at 2020-10-23

完成品

完成品のWebアプリ

https://naughty-franklin-898e0a.netlify.app/
郵便番号7桁入力したら住所検索します。
検索ボタンクリックするたびに行追加して検索します。

参考にしたもの

【Vue.js】データ配列を使ってテーブルを動的に生成してみる。
Vue.jsを100時間勉強して分かったこと
HeartRails Geo API

コード(記事の下の方に完成品のCodePen置いてます)

・HTML

 <div class="row my-3">
    <div class="col-sm-6 mx-auto">
      <input class="form-control" v-model:value="text" placeholder="郵便番号を入力…"><br>
      郵便番号:{{ text }}<button v-on:click="addTask" class="btn btn-primary">検索</button>
    </div>
  </div>

  <table class="table table-striped">
    <thead>
      <tr>
        <th>都道府県</th>
        <th>市区町村</th>
        <th>町域</th>
        <th>緯度</th>
        <th>経度</th>
      </tr>
    </thead>
    <tbody>
        <tr v-for="address in addressList"> 
          <td>{{ address[0] }}</td>
          <td>{{ address[1] }}</td>
          <td>{{ address[2] }}</td>
          <td>{{ address[3] }}</td>
          <td>{{ address[4] }}</td>
        </tr>
    </tbody>
</table>

・Javascript

const app = new Vue({
    el: '#app', // Vueが管理する一番外側のDOM要素
    data: {
      // Vue内部で使いたい変数は全てこの中に定義する
      text: '',
      prefecture: '',
      addressList:[],
    },
    methods: {
      addTask: async function() {
        //郵便番号から住所情報取得
        try {
          const address = await axios.get('https://geoapi.heartrails.com/api/json?method=searchByPostal&postal=' + this.text);
          this.addressList.unshift([address.data['response']['location'][0].prefecture,address.data['response']['location'][0].city,address.data['response']['location'][0].town,address.data['response']['location'][0].x,address.data['response']['location'][0].y]);
        } catch (e){
          console.log('住所情報の取得に失敗:', this.todoList);
          console.error(e);
        }
      }
      ,
      clearAll: function() {
        console.log('検索履歴が削除されました。');
        this.addressList = [];
      }
    },
});

作成中のメモ

・axios.getの中のURL、node.jsはhttpでいけたけど、Vue.jsはhttpsじゃないとダメ(なぜ)

・CodePenの履歴(メモ書くのめんどくさいからCodePen分けて履歴にすればええやん。のスタイル。)
テーブル使ってないやつ
https://codepen.io/sawakoshi_yy/pen/MWeboLm

テーブル使ってるけど1行の中に追加されてるやつ
https://codepen.io/sawakoshi_yy/pen/eYzgpNN

完成品
https://codepen.io/sawakoshi_yy/pen/qBNROwY

・await使うなら、functionの前にasyncつける

12
11
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
12
11