Can´t load the "src" of an image via json (Vue.js)

javascript html json vue.js

1424 观看

2回复

12 作者的声誉

var topArticle=new Vue({
  el:'#toparticle',
  data:{topmostArticle:null},
  created: function(){
              fetch('topnews.json')
              .then(r=>r.json())
              .then(res=>{this.topmostArticle=$.grep(res,function(e){return e.topnews!==" "});
              console.log(this.topmostArticle);
              });
            }
        });
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>The greatest news app ever</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  </head>
  <body>

    <div id  ="toparticle">
      <img src="{{topmostArticle[0].topnews[0].img}}">
      <img src="2.jpg">
      "{{topmostArticle[0].topnews[0].img}}"
    </div>

    <script src="main.js"></script>

  </body>
</html>

I'm trying to load the source for an image with an external file but I'm facing some problems...the source isn't recognized in the image tag. The code should be correct because when the data is loaded outside the image tag it works nice. Anyone has any idea?? Thank you so much!

The first image is not loaded (because the src is transmitted via json), the second is ok and the third command, "{{topmostArticle[0].topnews[0].img}}", returns "2.jpg" so it's ok

JSON

           [{"topnews":[
                {"timestamp":"0",
                 "id":"2",
                 "cathegory":"2",
                 "headline":"2",
                 "text":"2",
                 "img":"2.jpg",
                 "url":"2.jpg",
                 "author":"2",
                 "comments":"2"
                },
                {"timestamp":"0",
                 "id":"2",
                 "cathegory":"3",
                 "headline":"3",
                 "text":"3",
                 "img":"3",
                 "url":"3",
                 "author":"3",
                 "comments":"3"
                 }
              ]}]

The question is why I can't load the src directly through json? Please click on the links below(web view) for more clarity!

  [web view][1]

  [1]: https://i.stack.imgur.com/gbFeq.png
作者: j.joe 的来源 发布者: 2017 年 12 月 27 日

回应 2


0

302 作者的声誉

Try changing the way that you bind the attribute:

<img :src="topmostArticle[0].topnews[0].img">
作者: Haroon R. 发布者: 2017 年 12 月 27 日

2

170 作者的声誉

Easiest way to get the image

<img :src="require(`@/assets/${topnews.img}`)" alt="Top News" />
作者: Kapil Chhabra 发布者: 2019 年 2 月 19 日
32x32