如何从 json 文件将 src 路径添加到 vue 组件中

How to add src path into vue component from json file

如果我从 json 文件获取路径,如何渲染图像。默认我使用 require('../assets/img/item-image.png')。但我不知道,在这种情况下如何使用它

组件:

<div v-for="(item, index) in items">
    <img :src="item.src">
</div>

<script>
    import axios from 'axios'

    export default {
        name: 'componentName',
        data () {
            return {
                items: null   
            }
        },
        mounted () {
            axios
            .get('./test.json')
            .then(response => (this.items = response.data))
        }
    }
</script> 

JSON 文件:

    [
        {
            "id": 1,
            "title": "item title",
            "src": "../assets/img/item-image.png",
            "alt": "item-image",
            "text": "item body"
        }
    ]

您必须添加require

<img :src="require(item.src)">

您需要继续使用 require() 以便让 Webpack 知道在捆绑时包含您的图像。

因为 Webpack 在编译时打包,而你的图片只在运行时才知道,所以最好保持部分路径静态,这样 Webpack 就可以乐观地包含正确的文件。

例如,如果您的所有图片都在 ../assets/img 下,则最佳选择如下所示

async mounted () {
  const pathRegex = /^\.\.\/assets\/img\//
  const { data } = await axios.get("./test.json")
  this.items = data.map(item => ({
    ...item,
    src: require(`../assets/img/${item.src.replace(pathRegex, "")}`)
  }))
}

然后 Webpack 将捆绑 ../assets/img 下的每个文件,并且在运行时将能够解析您提供的路径。

https://webpack.js.org/guides/dependency-management/#require-with-expression

我就是这样解决的。使用上面的正则表达式将 require 添加到 json 中的 src 属性时,我一直收到错误消息。这就是我所做的,它对我有用。

我正在使用 fetch() 阅读我正在使用 json-server 观看的 json。当您使用 res.json() 转换它时,json 基本上是一个对象数组 (cokeImages)。

{
  "cokeImages": [
            { 
                "title": "Cocacola Life", 
                "description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
                "src": "../assets/cocacola-cans/cocacola-life.png", 
                "id": 1, 
                "name": "cocacola-life",
                "nutrition": [
                    { "title": "sodium", "value": "150 cl", "percent": "25%" },
                    { "title": "Total Fats", "value": "0g", "percent" : "0%" },
                    { "title": "sodium (mg)", "value": "40mg", "percent": "0%"},
                    { "title": "potasium", "value": "4g", "percent": "0%" },
                    { "title": "calcium", "value": "0g", "percent": "0%"}
                ]
            },
            { 
                "title": "Cocacola Zero", 
                "description": "Lorem ipsum no sicut anon in aquila no ager. In homines ad majorem tempus avis, et cum in pecunia imoten tua",
                "src": "../assets/cocacola-cans/cocacola-zero.png", 
                "id": 2, 
                "name": "cocacola-zero",
               ... (and so on)...


如您所见,每个对象中的名称属性也是我在每个图像中使用的名称src。 这是我在 map() 方法中使用的名称 属性 将 require 附加到每个 src.

mounted(){
      fetch("http://localhost:3000/cokeImages")
      .then(response => response.json())
      .then(arrayOfOjects => {
        console.log(arrayOfObjects)
        this.cokeImages = data.map(eachObject => {
          return {...eachObject, src: require(`../assets/cocacola-cans/${eachObject.name}.png`)}
        })
        console.log(this.cokeImages)
      })
      .catch(err => {
        console.log(err.message)
      })
    }