如何从json文件向vue组件添加src路径

问题描述

如果我从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(),以便让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

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

我就是这样解决的。使用上面的正则表达式将 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","percent": "0%"}
                ]
            },{ 
                "title": "Cocacola Zero","src": "../assets/cocacola-cans/cocacola-zero.png","id": 2,"name": "cocacola-zero",... (and so on)...


如您所见,每个对象中的 name 属性也是我在每个图像中使用的名称 src。 我在 map() 方法中使用了 name 属性将 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)
      })
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...