1

I have got a undefined when I alert the param fetching from ajax using vue.js, here is my code.

test.json return:

[
  {isActive: false,name: test}
]

js:

new Vue({
el: '#viewport',
data: {

    test_data: []
},
mounted: function () {
    this.fetchTestData();
},
methods: {
    fetchTestData: function () {
        $.get(test.json, function (data) {

            this.test_data = data;
            alert(this.test_data.isActive);
        });

    }
}
});

I am beginner of vue.js, hope have a reply, thanks.

9
  • test_data is an array. Try this.test_data[0].active Commented Nov 10, 2016 at 8:13
  • Hi Rajesh, thanks for reply, but also undefined. Commented Nov 10, 2016 at 8:20
  • 1
    Can you check what data logs. If its string, you might need to parse it to object using JSON.parse Commented Nov 10, 2016 at 8:21
  • you means this? this.test_data = JSON.parse(data); Commented Nov 10, 2016 at 8:37
  • Yup. If you are sending data as string, you will need to convert in to object Commented Nov 10, 2016 at 8:39

1 Answer 1

1

If you are fetching this data from that test.json file, first it need to be like that because that's not validate json:

[
  {
    "isActive": false,
    "name": "test"
    }
]

and you need to use bind because this not referring to the Vue instance

    fetchTestData: function () {
        $.get('test.json', function (data) {
            this.test_data = data;
            alert(this.test_data[0].isActive);
        }.bind(this));
    }

and accessing the data like that this.test_data[0].isActive because it's an array

Sign up to request clarification or add additional context in comments.

3 Comments

exactly the [0] because the array. or you can give this.test_data = data[0] and alert(this.test_data.isActive);
I have follow the above step, alert this.test_data display correct data, but alert this.test_data.isActive display undefined.
@Winston notice the [0] because it's an array, did you try that?

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.