如何通过请求在VueJS应用中显示数据?

时间:2019-03-06 14:49:50

标签: api vue.js request render

我这样做是为了尝试使用Vue.js在页面中呈现数据,但是它不起作用。

控制台错误:“属性或方法'PROPERTY_NAME'未在实例上定义,但在渲染期间被引用。”

*“ get”功能来自项目中正在使用的Fetch API。不想添加Vue推荐的AXIOS。

var app6 = new Vue({
  el: "#my-id",
  data: null,
  mounted: function() {
    get('http://www.mocky.io/v2/5c7fd404330000c6378483fe')
    .then(function(response){
      this.data = response;
      console.log('success');
    }).catch(function(){
      console.log('error');
    });
  }
});

(如果我将对象直接放在“数据”上,它可以正常工作,但它必须来自外部API)

var app6 = new Vue({
  el: "#detalle-equipos",
  data: {
    "producttitle": "iPhone XR",
    "productcolor": "red",
    "productcapacity": "64GB",
    "slides": [
      {
        "src":"../../assets/resources/images/smartphone1.jpg",
        "alt":"smartphone 1",
      },
      {
        "src":"../../assets/resources/images/smartphone2.jpg",
        "alt":"smartphone 2",
      },
      {
        "src":"../../assets/resources/images/smartphone3.jpg",
        "alt":"smartphone 3",
      },
      {
        "src":"../../assets/resources/images/smartphone4.jpg",
        "alt":"smartphone 4",
      },
    ]
  },
  mounted: function() {
    get('http://www.mocky.io/v2/5c7fd404330000c6378483fe')
    .then(function(response){
      this.data = response
      console.log('success')
    }).catch(function(){
      console.log('error')
    });
  }
});

好吧,帮助...

1 个答案:

答案 0 :(得分:2)

this中的

then block不是Vue实例。您可以使用箭头功能

mounted: function() {
  get('http://www.mocky.io/v2/5c7fd404330000c6378483fe')
  .then((response) => {
    this.slides = response.ATTslides
    this.producttitle = response.ATTproducttitle

  }).catch(function(){
    console.log('error')
  });
}