Vue.component没有将作为ajax传递的数据注册到字符串模板

时间:2017-02-27 04:06:15

标签: javascript ajax vuejs2 axios

Vue的新手,显然缺少一些简单的东西。我有以下代码,一旦返回AJAX GET调用,我希望创建一个简单的产品名列表。

main.js

Vue.component('products', {
  template: `
    <ul>
      <li v-for='product in products'>{{product.name}}</li>
    </ul>
  `,
  data() {
    return { products: [] }
  },
  created() {
    this.fetchProducts();
  },
  methods: {
    fetchProducts() {
        axios.get('/api/products').then(function(response){
            console.log(response.data);
            this.products = response.data;
        });
    }
  }
});

new Vue({ el: '#app' });

的index.html

<html>
  <body>

     <div id='app'></div>

     <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
     <script src="https://unpkg.com/vue@2.1.6/dist/vue.js"></script>
     <script src="main.js"></script>
  </body>
</html>

我知道ajax调用会返回一个对象数组,因为我看到它们已经登录到控制台,因此后端没有错误。我猜测我没有正确地将ajax响应数据挂回到模板中。

由于

编辑&amp; ANSWER

AJAX方法失去了对&#34;这个&#34;的正确引用。关键词。 main.js 的这些解决方案中的任何一个都可以修复它。

Vue.component('products', {
  template: ` ... `,
  data() { ... },
  created() {
    this.fetchProducts(); // or this.fetchProducts2();
  },
  methods: {
    fetchProducts() {
        var self = this;
        axios.get('/api/products').then(function(response){
            console.log(response.data);
            self.products = response.data;
        });
    },
    fetchProducts2() {
        axios.get('/api/products').then(response => {
            console.log(response.data);
            this.products = response.data;
        });
    }
  }
});

new Vue({ el: '#app' });

0 个答案:

没有答案