Получение данных остальных API в таблицу начальной загрузки Vue и нумерацию страниц - PullRequest
0 голосов
/ 29 июня 2019

Я использую остальные API-интерфейсы Itunes для передачи данных в мое приложение, у меня возникли проблемы с переносом данных в таблицу, структура остальных API выглядит следующим образом:

{resultCount: 4, results: Array(4)}

Пока я пробовал следующее:

<div class="overflow-auto">
            <b-pagination
              v-model="currentPage"
              :total-rows="rows"
              :per-page="perPage"
              aria-controls="my-table"
            ></b-pagination>

            <p class="mt-3">Current Page: {{ currentPage }}</p>

            <b-table
              id="my-table"
              v-for="(result, index) in result"
              :key="index"
              :fields="fields"
              :per-page="perPage"
              :current-page="currentPage"
              small
            ></b-table>
          </div>

<script>
import List from "../components/myList.vue";

export default {
  name: "Hero",
  components: {
    List
  },
  data: function() {
    return {
      fields: [
        {
          key: "artistName",
          label: "Artist"
        },
        {
          key: "collectionName",
          label: "Song title"
        }
      ],
      title: "Simple Search",
      isActive: true,
      intro: "This is a simple hero unit, a simple jumbotron-style.",
      subintro:
        "It uses utility classes for typography and spacing to space content out.",
      result: [],
      errors: [],
      List: [],
      search: "",
      loading: "",
      message: false,
      isValidationAllowed: false,
      loadingClass: "loading",
      errorTextClass: "error-text",
      disableButton: false,
      perPage: 3,
      currentPage: 1
    };
  },

  watch: {
    search: function(val) {
      if (!val) {
        this.result = [];
      }
    }
  },

  computed: {
    validated() {
      return this.isValidationAllowed && !this.search;
    },
    isDisabled: function() {
      return !this.terms;
    },
    rows() {
      return this.result.length;
    }
  },

  methods: {
    getData: function() {
      this.isValidationAllowed = true;
      this.loading = true;
      fetch(`https://itunes.apple.com/search?term=${this.search}&entity=album`)
        .then(response => response.json())
        .then(data => {
          this.result = data.results;
          this.loading = false;
          /* eslint-disable no-console */
          console.log(data);
          /* eslint-disable no-console */
        });
    },

    toggleClass: function() {
      // Check value
      if (this.isActive) {
        this.isActive = false;
      } else {
        this.isActive = true;
      }
    },

    refreshPage: function() {
      this.search = "";
    },
    addItem: function(result) {
      result.disableButton = true; // Or result['disableButton'] = true;
      this.List.push(result);
      /* eslint-disable no-console */
      console.log(result);
      /* eslint-disable no-console */
    },

    resizeArtworkUrl(result) {
      return result.artworkUrl100.replace("100x100", "160x160");
    }
  },
  mounted() {
    if (localStorage.getItem("List")) {
      try {
        this.List = JSON.parse(localStorage.getItem("List"));
      } catch (err) {
        console.err(err);
      }
    }
  }
};
</script>

Я получаю только [Object Object] при просмотре визуализированной страницы, поэтому либо я не нацеливаюсь на правильный элемент, либо он не подходит: следующий код работает за пределами нумерации и таблицы начальной загрузки.

<div v-for="(result, index) in result" :key="index">
            <div class="media mb-4">
              <img
                :src="resizeArtworkUrl(result)"
                alt="Album Cover"
                class="album-cover align-self-start mr-3"
              >
              <div class="media-body">
                <h4 class="mt-0">

                  <button
                    type="button"
                    class="btn btn-primary btn-lg mb-3 float-right"
                    v-on:click="addItem(result)"
                    :disabled="result.disableButton"
                  >
                    <font-awesome-icon icon="plus"/>
                  </button>

                  <b>{{result.collectionName}}</b>
                </h4>
                <h6 class="mt-0">{{result.artistName}}</h6>
                <p class="mt-0">{{result.primaryGenreName}}</p>
              </div>
            </div>
          </div>

Любая помощь будет хорошей.

1 Ответ

0 голосов
/ 29 июня 2019

В вашем шаблоне есть две переменные с одинаковым именем:

<div v-for="(result, index) in result" :key="index">

попробуйте изменить имя result следующим образом:

<div v-for="(item, index) in result" :key="index">
    <div class="media mb-4">
        <img
        :src="resizeArtworkUrl(item)"
        alt="Album Cover"
        class="album-cover align-self-start mr-3"
        >
        <div class="media-body">
        <h4 class="mt-0">

            <button
            type="button"
            class="btn btn-primary btn-lg mb-3 float-right"
            v-on:click="addItem(item)"
            :disabled="item.disableButton"
            >
            <font-awesome-icon icon="plus"/>
            </button>

            <b>{{item.collectionName}}</b>
        </h4>
        <h6 class="mt-0">{{item.artistName}}</h6>
        <p class="mt-0">{{item.primaryGenreName}}</p>
        </div>
    </div>
</div>
...