1

New to Vue and obviously missing something simple. I have the following code which I am expecting to create a simple list of product names once an AJAX GET call is returned.

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>

I know the ajax call returns an array of objects because I see them logged to the console so there is not an error on the backend. I'm guessing I'm just not hooking the ajax response data back into the template correctly.

Thanks

EDIT & ANSWER

The AJAX method lost its correct reference to "this" keyword. Either of these solutions for main.js fix it.

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' });
SciGuyMcQ
  • 993
  • 6
  • 21
  • 1
    Quick answer... change `.then(function(response){` to `.then(response => {` – Phil Feb 27 '17 at 04:10
  • Yep, that was it. I sort circuited back to using the old syntax for the callback and that through off the "this" reference. – SciGuyMcQ Feb 27 '17 at 04:15

0 Answers0