0

I'm trying to fetch data from an API and then display it with vue using the mounted() method, but when I try it, it says that this basically is not defined.

I'm not using NodeJS.

<script>
"use strict";

    (function() {
        var app = new Vue({
            el: "#app",

            data () {
                return {
                    books: null
                }
            },

            mounted () {
                var api = fermata.json("/api/books");
                api.get(function(err, res) {
                    if(res.success) {
                        this.books = res.result;
                    }
                });
            }
        });
    })();
</script>

Which gives me the following error

Uncaught TypeError: Cannot set property 'books' of undefined

Fermata

Jeffrey Anderson
  • 409
  • 2
  • 5
  • 10
  • context issue. uses arrow like `api.get((err, res)=> {})` instead, or save the Vue instance to one variable first like `let _self=this`, then inside the callback of your api.get, uses `_self.book` – Sphinx Sep 04 '18 at 17:20
  • Okay that makes sense, thank you! – Jeffrey Anderson Sep 04 '18 at 17:22

1 Answers1

0

your code should be like this, create alias for this keyword, withing api.get you may loose this scope.

mounted () {
        var api = fermata.json("/api/books");
        var _this = this;
        api.get(function(err, res) {
            if(res.success) {
                _this.books = res.result;
            }
        });
    }
Amruth
  • 5,792
  • 2
  • 28
  • 41