遍历Vue.js静态目录中的资产 [英] Looping through assets in Vue.js static directory

查看:59
本文介绍了遍历Vue.js静态目录中的资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Vue中创建了一个简单的应用(使用Webpack模板),其中包含轮播.我想做的是循环遍历static/images中的所有图像以创建该轮播.我知道这可能是一个愚蠢的问题,但是我将如何去做呢?我需要执行GET请求吗?

I've created a simple app in Vue (using the Webpack template) that has a carousel in it. What I would like to do is loop through all of the images in static/images to create that carousel. I know this is probably a dumb question, but how would I go about doing this? Do I need to perform a GET request?

我要问的原因是因为我要将其交给要托管在其服务器上的客户端.他们希望能够根据需要向轮播中添加其他图像.

The reason I'm asking is because I'm going to hand this off to a client to be hosted on their server. They would like to be able to add additional images to the carousel themselves if needed.

任何帮助将不胜感激.

推荐答案

来自此

From this webpack documentation you can get all files in the directory or specific files based on a regex search pattern.

您可以执行以下操作:

var cache = {};

function importAll (r) {
  r.keys().forEach(key => cache[key] = r(key));
}

importAll(require.context('../components/', true, /\.js$/));

如果您需要服务器中的图像名称数组,可以执行以下操作:

If you a need an array of image names from the server you could do this:

<template lang="html">
   <div style="height: 100px">
     <div :key="key" v-for="(img, key) in images" >
       <img :src="imageDir + key.substr(1)" class="" >
     </div>
    </div>
 </template>
<script>
export default {
  data() {
    return {
      imageDir: "/your/path/to/images/", // you know this already just from directory structure
      images: {}
    }
  },

  mounted() {
    this.importAll(require.context(this.imageDir, true, /\.png$/))
  },
  methods: {
    importAll(r) {
      var imgs = {}
      r.keys().forEach(key => (imgs[key] = r(key)))
      this.images = imgs
    }
  }
}
</script>

我不能完全确定我是否正确执行了操作,但是它会从目录中返回图像并按预期显示它们.

I am not entirely sure if I am doing it correctly but it return the images from the directory and displays them as expected.

这篇关于遍历Vue.js静态目录中的资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆