Как получить данные в шаблоне vue, вызвав функцию - PullRequest
1 голос
/ 28 января 2020

У меня есть несколько магазинов. Эти магазины продают различные товары. На странице должен отображаться список магазинов, а также список категорий товаров, которые продает магазин.

Данные Console.log поступают, но я не могу отобразить категорию продуктов магазина список пар

   <template>               
        <div class="store">
            <div v-for="store in stores" :key="store.id" :set="products = getProducts(store.id)">
<h2>{{store.name}}</h2>
//Other Store info
<ul>
<li v-for="product in products">
{{product.category.name}}
//This data is not Show
</li>
</ul>

             </div>
        </div>

</template>

<script>
    export default {
        data() {
            return {
                stores: []

            }
        },
        mounted() {
            var app = this;
            axios.get('/axios/allstore/')
                .then(function (response) {
                    app.stores = response.data;
                    console.log(response.data);
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        methods: {
            getProducts(storeID) {
                var pp = this;
                axios.get('/axios/storeproducts/' + storeID, {
                        params: {
                            storeID: storeID,
                        }
                    })
                    .then(function (response) {
                        console.log(response.data);
                        return response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            }
        },
    }

</script>

Спасибо, Advance.

1 Ответ

0 голосов
/ 28 января 2020

Я бы выбрал совершенно другой подход, поскольку, прежде всего, используя :set, ваши http-запросы будут запускаться всякий раз, когда происходит обнаружение изменений. Вместо этого соберите все данные при визуализации компонента:

created() {
  this.getStores();
},
methods: {
  getProducts(id) {
    return axios.get("...")
      .then(response => response.data)
  },
  getStores() {
    // first get stores, you can also use async await instead, if you like
    axios.get("...").then(response => {
      this.stores = response.data;
      // gather all requests for each store to get products
      const reqs = this.stores.map(store => this.getProducts(store.id));
      axios.all(reqs).then(products => {
        // merge data
        this.stores = this.stores.map((store, i) => {
          return { ...store, products: products[i] };
        });
      });
    });
  }
}

Теперь для каждого магазина есть свойство products:

<div v-for="store in stores" :key="store.id">
  <h2>{{store.name}}</h2>
  <ul>
    <!-- choose a key, here just using index -->
    <li v-for="(product, index) in store.products" :key="index">
      {{product.category.name}}
    </li>
  </ul>
</div>

Что касается шаблона, убедитесь, что category.name фактически существует в объекте продукта.

...