Vue. js как il oop сгенерировать массив для добавления компонентов в dom в соответствии с элементами массива - PullRequest
0 голосов
/ 07 апреля 2020

Я создаю приложение, которое взаимодействует с API и извлекает данные, домашняя страница меняется каждый день, поэтому я не могу просто добавить к нему stati c компонентов, мне нужно создать его в соответствии с данными, полученными из api.

У меня есть компонент для домашней страницы, который называется Home.vue

. Этот компонент может иметь одну или несколько каруселей в зависимости от данных, которые я получаю.

у меня также есть Carousel.vue, который отвечает за отображение изображений, и у него есть свой собственный props.

вопрос:

Как добавить компонент в дом от l oop

это Home.vue, где я делаю loop:

    <template>
      <div>


        <!--I Need The Loop right here-->


      </div>
    </template>

    <script>

      export default {
        components: {},
        data() {
          return {
            page_content: [],
            widgets: [],

          }
        },
        created() {
          this.getHomeContent();
        },
        methods:
          {

            getHomeContent() {
              window.axios.get(window.main_urls["home-content"]).then(response => {
                this.page_content = JSON.parse(JSON.stringify(response.data));
                console.log(this.page_content);
                for (let index in this.page_content) {
                  switch (this.page_content[index].type) {
    //                if type is banner
                    case 'banner':
                      switch (this.page_content[index].display) {
    //                    if display is carousel
                        case 'carousel':
                          console.log('carousel')
                          // end if display is carousel
                          this.widgets.push({
                            'type': 'Carousel',
                            'images': this.page_content[index].items,

                          })
                      }

    //                  end if type is banner

                  }
                }

              });
            }
          }
      }
    </script>

и это Carousel.vue, что мне нужно импортировать при необходимости с пропуском :


    <template>
    <div>
        <div >
          <VueSlickCarousel>
            <div v-for="image in images">
              <img src="{{img}}">
            </div>
          </VueSlickCarousel>
        </div>
    </div>
    </template>
    <script>
      import VueSlickCarousel from 'vue-slick-carousel'
      import 'vue-slick-carousel/dist/vue-slick-carousel.css'

      import 'vue-slick-carousel/dist/vue-slick-carousel-theme.css'
      export default
      {
        components: {VueSlickCarousel},
        name:'Carousel',
        props:[

          'images'
        ],

        methods:
          {

          }
      }
    </script>

как добавить Carousel.vue компонент к Home.vue динамически что-то вроде :

if(data.display == 'carousel')
{
   <carousel images="data.images"></carousel>
}

Ответы [ 2 ]

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

Это правильный ответ!


    <template>
      <div>


        <template v-for="widget in widgets">

          <div v-if="widget.type == 'carousel'" :key="widget.type">
            <carousel
              :images="widget.images"
              :arrows ="widget.arrows"
              :dots = "widget.dots"
            >

            </carousel>
          </div>

        </template>


      </div>
    </template>

    <script>
      import Carousel from './widgets/Carousel.vue'
      export default {
        components: {Carousel},
        data() {
          return {
            page_content: [],
            widgets: [],

          }
        },
        created() {
          this.getHomeContent();
        },
        methods:
          {

            getHomeContent() {
              window.axios.get(window.main_urls["home-content"]).then(response => {
                this.page_content = JSON.parse(JSON.stringify(response.data));
                console.log(this.page_content);
                for (let index in this.page_content) {
                  switch (this.page_content[index].type) {
    //                if type is banner
                    case 'banner':
                      switch (this.page_content[index].display) {
    //                    if display is carousel
                        case 'carousel':
                          console.log('carousel')
                          // end if display is carousel
                          this.widgets.push({
                            'type': 'carousel',
                            'arrows':true,
                            'dots':true,
                            'images': this.page_content[index].items,
                          })
                      }

    //                  end if type is banner

                  }
                }

              });
            }
          }
      }
    </script>

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

Импортируйте компонент в свой дом. vue:

import Carousel from './Carousel.vue'

export default {
    components: {Carousel},
}

Тогда l oop в вашем шаблоне:

<carousel v-for="(widget,index) in widgets" :key="index" :images="widget.images"/>

Лучше всего использовать widget.id вместо Индекс для key проп

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...