vue js ax ios не может прочитать свойство 'данные' из неопределенного - PullRequest
0 голосов
/ 24 апреля 2020

Я пытаюсь заставить json отображаться в карточках или списке после поиска. Поисковая часть, кажется, работает, так как я вижу вызов API с текстом, написанным в окне поиска в консоли. но ничего не отображается, и я получаю эту ошибку TypeError: Невозможно прочитать свойство 'data' из undefined. Я не думаю, что получаю правильный путь json.

приложение. vue

  <template>
  <div id="app">
    <Header/>
    <SearchForm v-on:search="search"/>
    <SearchResults
      v-if="results.length > 0"
      v-bind:results="results"
      v-bind:reformattedSearchString="reformattedSearchString"
    />
    <Pagination
      v-if="results.length > 0"
      v-bind:prevPageToken="api.prevPageToken"
      v-bind:nextPageToken="api.nextPageToken"
      v-on:prev-page="prevPage"
      v-on:next-page="nextPage"
    />
  </div>
</template>

<script>
import Header from './components/layout/Header';
import SearchForm from './components/SearchForm';
import SearchResults from './components/SearchResults';
import Pagination from './components/Pagination';
import axios from 'axios';

export default {
  name: 'app',
  components: {
    Header,
    SearchForm,
    SearchResults,
    Pagination
  },

   data() {
    return {
      results: [],
      reformattedSearchString: '',
      api: {
        baseUrl: 'https://geodeepdive.org/api/v1/articles?',
        max: 10,
        q: '',
        prevPageToken: '',
        nextPageToken: ''
      }
    };
  },


   methods: {
    search(searchParams) {
      this.reformattedSearchString = searchParams.join(' ');
      this.api.q = searchParams.join('+');
      const { baseUrl, q, max} = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}`;
      this.getData(apiUrl);

    },

    prevPage() {
      const { baseUrl, q, max, prevPageToken } = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}&pageToken=${prevPageToken}`;
      this.getData(apiUrl);
    },

    nextPage() {
      const { baseUrl, q, max,nextPageToken } = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}&pageToken=${nextPageToken}`;
      this.getData(apiUrl);
    },

    getData(apiUrl) {
      axios
        .get(apiUrl)

        .then(res => {
          this.results = res.success.data;
          this.api.prevPageToken = res.success.data.prevPageToken;
          this.api.nextPageToken = res.success.data.nextPageToken;
        })
        .catch(error => console.log(error))
    }

  }
};
</script>

результаты поиска

<template>
  <div class="container mb-3">
    <div class="d-flex mb-3">
      <div class="mr-auto">
        <h3>Search Results for "{{ reformattedSearchString }}"</h3>
      </div>
      <div class="btn-group ml-auto" role="group">
        <button
          @click="changeDisplayMode('grid')"
          type="button"
          class="btn btn-outline-secondary"
          v-bind:class="{ active: displayMode === 'grid' }"
        >
          <i class="fas fa-th"></i>
        </button>
        <button
          @click="changeDisplayMode('list')"
          type="button"
          class="btn btn-outline-secondary"
          v-bind:class="{ active: displayMode === 'list' }"
        >
          <i class="fas fa-list"></i>
        </button>
      </div>
    </div>

    <div class="card-columns" v-if="displayMode === 'grid'">
      <div class="card" v-bind:key="result.link.url" v-for="result in results">
        <ArticleGridItem v-bind:result="result"/>
      </div>
    </div>
    <div v-else>
      <div class="card mb-2" v-bind:key="result.link.url" v-for="result in results">
        <ArticleListItem v-bind:result="result"/>
      </div>
    </div>
  </div>
</template>

<script>
import ArticleListItem from './ArticleListItem';
import ArticleGridItem from './ArticleGridItem';

export default {
  name: 'SearchResults',
  components: {
    ArticleListItem,
    ArticleGridItem
  },
  data() {
    return {
      title: 'Search Results',
      displayMode: 'grid'
    };
  },
  methods: {
    changeDisplayMode(displayMode) {
      this.displayMode = displayMode;
    }
  },
  props: ['results', 'reformattedSearchString']
};
</script>

json

{
success: {
    v: 1,
    data: [
       {
         type: "article",
         _gddid: "5ea0b2b3998e17af826b7f42",
         title: "The current COVID-19 wave will likely be mitigated in the second-line European countries",
         volume: "",
         journal: "Cold Spring Harbor Laboratory Press",
         link: [
            {
               url: "https://www.medrxiv.org/content/10.1101/2020.04.17.20069179v1",
               type: "publisher"
             }
         ],
         publisher: "bioRxiv",
         author: [
            {
               name: "Samuel Soubeyrand"
             }

         ],
        pages: "",
        number: "",
        identifier: [
          {
              type: "doi",
              id: "10.1101/2020.04.17.20069179"
           }
        ],
       year: "2020"
      }
    ]
 }

}

1 Ответ

0 голосов
/ 26 апреля 2020

вам не хватает объекта res.data

    this.results = res.data.success.data;
    this.api.prevPageToken = res.data.success.data.prevPageToken;
    this.api.nextPageToken = res.data.success.data.nextPageToken;
...