Нужна помощь в ограничении массива / оптимизации ответов Axios - PullRequest
2 голосов
/ 17 марта 2019

У меня есть что-то вроде /url/{category}.

. Это код для извлечения некоторых из них на главной странице:

export default {
    data() {
        return {
            topnews:[],
            newsfive:[],
            categories: { 
                tshirts:'',
                shirts:'',
                shoes:'',
                useful:'', 
            }
        }
    },
    methods() {
        async getAll(){
            axios.all([
                axios.get(`/topnews`),
                axios.get(`/news`),
                axios.get(`/tshirts`),
                axios.get(`/shirts`),
                axios.get(`/shoes`),
                axios.get(`/useful`)])
                .then(axios.spread((topnews, news, tshirts, shirts, shoes, useful) => {
                    news.data.length = 5;
                    tshirts.data.length = 5
                    shirts.data.length = 5
                    shoes.data.length = 5
                    useful.data.length = 5
                    // How to limit these appropriately? 

                    this.newsfive = news.data;
                    this.topnews = topnews.data;

                    this.categories = {
                        tshirts: tshirts.data,
                        shirts: shirts.data,
                        shoes: shoes.data,
                        useful: useful.data,
                    }
                })).catch(error => console.log(error))
        }
    }
    created()  {
        this.getAll() 
    }
}

Это работает, но если я изменю маршрут на/tshirts и используя браузер обратно на главную страницу, я получаю:

свойство typeerror content только для чтения

Также возможно объединить это в один массиввместо того, чтобы создавать 7 разных div, например:

<div v-for="tshirts,key in categories.tshirts" :key="categories.tshirts.slug">
    <img :src="tshirts.thumb" class="img-responsive" width=100%/>
    <p>{{tshirts.title}}</p>
</div>

Вместо этого есть что-то вроде отфильтрованного вычисленного ответа axios, а затем просто использовать один div?

<div v-for="item,key in categories(tshirts)" :key="categories(item.slug)">

Как я могу ограничить массив axiosразмер ответа?

1 Ответ

2 голосов
/ 18 марта 2019

Создать Category.vue для отображения только содержимого категории

<template>
  <div v-for="(item, key) in category" :key="item.slug">
      <img :src="item.thumb" class="img-responsive" width=100% />
      <p>{{ item.title }}</p>
  </div>
</template>
<script>
export default {
    data() {
        return {
            category: { }
        }
    },
    methods() {
        getCategory() {
          axios.get(`/${this.$route.params.category}`)                
               .then((response) => {
                  this.category = response.data.slice(0, 5);                    
               }).catch(error => console.log(error));
        }
    }
    created()  {
        this.getCategory() 
    }
}
</script>

И в App.vue добавить router-link ко всем категориям

<template>
   <nav>
      <router-link to="{ name: 'category', params: {category: 'tshirts'} }">T-Shirts</router-link>
      <router-link to="{ name: 'category', params: {category: 'shirts'} }">Shirts</router-link>
     <!-- and other -->
   </nav>
   <main>
      <router-view></router-view>
   </main
</template>

Не подделывать о vue-router

import Category from "./Category.vue"

routes = [
  {
    name: "category",
    path: "/:categoryId",
    component: Category
  }
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...