10

I'm trying to receive json in my vue.js app like this:

  new Vue({
            el: 'body',
            data:{
                role: '',
                company: '',
                list:[],
                created: function() {
                  this.getJson();
                },
                methods: {
                    getJson: function(){
                        $.getJSON('http://domain.dev/data',function(task){
                          this.list = task;
                        }.bind(this));
                    }
                }
            }
        });

But the result is null? When I test this in postman the url returns json. What am I doing wrong here?

EDIT:

JSON (testdata):

{"EmployeeId":1,"RoleId":5,"DepartmentId":6,"InternId":1,"FirstName":"Zoe","LastName":"Altenwerth","Bio":"Quidem perferendis.","email":"[email protected]","LinkedIn":"[email protected]","Gender":0,"password":"$2y$10$bbUlDh2060RBRVHSPHoQSu05ykfkw2hGQa8ZO8nmZLFFa3Emy18gK","PlainPassword":"gr^S=Z","remember_token":"D528C0Ba1Xzq3yRV7FdNvDd8SYbrM0gAJdFUcOBq4sNEJdHEOb2xIQ0geVhZ","Address":"0593 Dallin Parkway Apt. 499\nBotsfordborough, MT 12501","Zip":"21503-","City":"East Janiston","ProfilePicture":null,"BirthDate":"2002-10-13 00:00:00","StartDate":"1995-11-09 21:42:22","EndDate":"2011-01-27","Suspended":0,"created_at":"2016-02-29 12:21:42","updated_at":"2016-03-02 11:53:58","deleted_at":null,"role":{"RoleId":5,"RoleName":"Superadministrator","Description":"Mag administrators toevoegen en bewerken","deleted_at":null,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},"department":{"DepartmentId":6,"CompanyId":12,"DepartmentName":"com","Description":"Accusantium quae.","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41","company":{"CompanyId":12,"CompanyName":"Dare, Bailey and Bednar","Logo":null,"Address":"85762 Tabitha Lights\nWest Jettie, AK 20878-2569","Zip":"29601","City":"Traceside","KvKNumber":"84c70661-9","EcaboNumber":"fdee61e3-a22d-3332-a","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41"}}}

4 Answers 4

22

Here is a little example of how to load external JSON data into your component:

a.json:

{"hello": "welcome"}

index.html:

<div id="app">
    <pre>{{ json.hello }}</pre>
</div>

<script type="text/javascript">
var app = new Vue({
    el: '#app',
    data: {
        json: null
    }
});
$.getJSON('http://localhost/a.json', function (json) {
    app.json = json;
});
</script>

--- Edited ---

Or with created event:

<script type="text/javascript">
new Vue({
    el: '#app',
    data: {
        json: null
    },
    created: function () {
        var _this = this;
        $.getJSON('http://localhost/a.json', function (json) {
            _this.json = json;
        });
    }
});
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

What is the meaning of _this ? Why we cannot use this?
@SuatAtanPhD There are 3 ways to access this. 1) using variable like _this; 2) using arrow function () => {...}; 3) using bind function(){}.bind(this). I choose first option.
@vbarbarosh how does _this connect to data?, in normal vue apps this.json = json works, but not in this instance. (your method does work, just curious how)
Two lines above - var _this = this;.
I'm new to vue - and looking at it as a replacement to jquery for my purposes. Somehow using .getJSON inside vue feels wrong.. why not axios? vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
|
14

Building on @vbarbarosh's answer, but using the browser's fetch api:

a.json:

{"hello": "welcome"}

index.html:

<div id="app">
    <pre>{{ json.hello }}</pre>
</div>

<script type="text/javascript">
new Vue({
    el: '#app',
    data: {
        json: null
    },
    created: function () {
      fetch("/a.json")
        .then(r => r.json())
        .then(json => {
          this.json=json;
        });
    }
});
</script>

3 Comments

Any particular reason you went with created rather than beforeCreate? (The Vue lifecycle diagram shows all available hooks.)
I have issues running this code in IE11 on this line .then(r => r.json()) even after having polyfill.
6

You have to bind this to the outer function, too.

getJson: function () { ...}.bind(this)

5 Comments

Does task contains any data?
When I console.log(task); it's not showing anything in the console?! (And I included jquery)
it can't be the problem because it returns json please see my edit.
Then your Ajax request seems to fail somehow. Anyway regarding you initial question you can check if this.list = 'test' works to seperate your problems.
Ohhh I found it a beginner mistake -_- I had created() within the data section. Thanks for your help.
1

Update for Vue3

const app = Vue.createApp({
    data: function() {
        return {
            role: '',
            company: '',
            list:[]
        };
    },
    beforeMount: function() {
        this.getJson();
    },
    methods: {
        getJson: function(){
            $.getJSON('http://domain.dev/data',function(task){
                this.list = task;
            }.bind(this));
        }
    }
});

const mountedApp = app.mount('body');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.