首页 > 解决方案 > 加载 Javascript 时不显示图像幻灯片

问题描述

我正在使用幻灯片,以便用户可以看到 globalgiving api 可能具有的任何额外图像。但是,问题是,当页面加载时,当您打开模式时,幻灯片不存在,除非您选择打开我在模式中实现的选项卡。但是,这些选项卡与幻灯片无关。

下面是我正在使用的 HTML 代码:

    <div v-if="projectData.images" class="
     <div class="slider_list">
       <img v-for="(src, index) in projectData.images.slice(0, 5)" :key="src" :src="src" v-show="index === active">
     </div>

     <button class="slider_prev" @click="change(active-1)">prev</button>
     <button class="slider_next" @click="change(active+1)">next</button>

     <ul class="slider_dots">
        <li v-for="(src, index) in projectData.images.slice(0, 5)" :key="src" :class="{active:index === active}" @click="change(index)">
           <button>{{index}}</button>
        </li>
     </ul>
</div>
<div v-else class="bigImage" :style="{backgroundImage: 'url(' + projectData.banner + ')'}"></div>

以下是我正在使用的 Javascript 代码:

change: function(index) {
      if (this.projectData.images.length < 5) {
        this.direction = index > this.active ? 1 : -1
        this.active = (index + this.projectData.images.length) % this.projectData.images.length
      } else if (this.projectData.images.length = 5) {
        this.direction = index > this.active ? 1 : -1
        this.active = (index + this.projectData.images.length) % this.projectData.images.length
      } else if (this.projectData.images.length > 5) {
        this.direction = index > this.active ? 1 : -1
        this.active = (index + this.projectData.images.length) % this.projectData.images.length
      }
    }

projectData是来自父组件的 Object 道具。

但是,当我注销时this.projectData,会显示完整的对象,其中包含图像。但是,如果我注销,this.projectData.images那么它就会出现undefined,我不确定为什么会这样。

这是父 javascript 代码:

if (project.imageGallerySize > 1) {
        axios.get(`https://api.globalgiving.org/api/public/projectservice/projects/${project.id}/imagegallery?api_key=71774a46-da0c-4748-a5ea-7001d6a47709`, {
          headers: {
            Accept: "application/json"
          }
        }).then(response => {
          projectObject['images'] = [];
          for (let i = 0; i < response.data.images.image.length; i++) {
            projectObject['images'].push(response.data.images.image[i].imagelink.filter(function(image) {
              if (image.size == 'orginal') {
                return true;
              }
            })[0].url);
          }
        }).catch(error => {
          console.log("Wrong", error)
        })
      }

如果有人可以请帮助,将不胜感激。

非常感谢!

标签: javascripthtmlvue.jsaxiosvue-component

解决方案


当您将反应式 vue 对象输出到控制台时,控制台不会立即显示其属性的值。控制台仅在您单击反应对象以显示它们时调用它们的“getter”函数。

在代码中:

console.log(this.projectData); // <-- the printed properties are only the getter functions, not their values
console.log(this.projectData.images); // <-- the output will be the current value of this.projectData.images

这可以解释控制台中看似矛盾的结果。

我猜测为什么会发生这种情况是因为您尝试this.projectData在 axios 请求完成之前使用。为了证明这一点,您可以添加console.log(this.projectData.images)到您的then()方法并查看输出(或使用调试器)。


推荐阅读