Edit
The Component.vue provided was part of a larger web app so I ripped out the relevant code for this question. What I didn't notice was a VERY tiny change I made in ripping out the code that had a very big impact.
There's a difference between:
mounted() {
// ....
}
and:
mounted: () => {
// ....
}
Upon careful investigation this morning I found this mistake in my code and I've updated the question to reflect the actual code that was failing.
Question
I may just be tired, but before going to bed I wanted to ask for help here and see if someone can find my issue. I have a very simple Vue component that isn't working:
Component.vue:
<template>
<div>
<p v-for="item in items">{{ item.text }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: []
};
},
mounted: () => {
var _this = this;
$.ajax("/items.json").done(result => {
_this.items = result;
});
}
};
</script>
items.json
[
{"text": "ABC"},
{"text": "XYZ"}
]
The paragraphs are never rendering. Upon inspection it looks like _this.items doesn't exist prior to setting it in the AJAX handler (I expect it to be an empty array) and _this.$data also doesn't exist
~Is the value of this different in the mounted method than elsewhere in Vue?~ Or did I make a simple mistake?
Writing the mounted function in this way (with the colon) causes the value of this to be different. Why is that?
done, reassigningthisisn't necessary. Try it without.setTimeoutinstead of$.ajax.$.ajaxto$.getJSON. Perhaps your server isn't delivering theitems.jsonfile with the correctContent-typeand jQuery is unable to determine the data type automatically. Also, how are you opening your app; viahttp://orfile:///?/items.jsonaccessible. This could be your web server setup.