So I am really new to this Vue.js
and what I am trying to achieve is simple, I am trying to append the results of this Ajax
request into my list
<div id="app">
<button v-on:click="buttonClick">Test</button>
<ul id="example-1">
<li v-for="t in test">
{{ t }}
</li>
</ul>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
'message': 'hello world',
'test': null
},
methods: {
buttonClick: function() {
axios.get('api/getdata')
.then(function(response) {
test = response.data;
//if this was Jquery I'd use $('li').append here
})
.catch(function(error) {
});
}
}
})
</script>
Now the problem is I don't know how to do it, my variable test
should hold all the data and then I should just loop it as I did, but how I trigger it again once I got the data?
EDIT: Just to clarify, I am not asking question about "this" and "self" I am asking on how to APPEND this data onto some HTML element
You need to reference the current instance to set
test
. Something like the following will work for you:And for some good information on how
this
works:How does the "this" keyword work?
Perhaps because you are used to working with a library like jQuery you are thinking in terms of appending something to the DOM. Vue is data driven, so if you have a list like yours...
And you have your property like...
If then you were to do something like this...
Since the data is already bound to your list with the
v-for
the moment you update thetest
array an item or items will be added to your list. You dont need to append anything. Vue watches and changes the list dynamically as the value oftest
changes.You may not have asked in those specific words, but they're key to doing what you want to do.
Your code is so close, you just need to understand JavaScript's variable scope. The line
test = response.data;
as-written is doing basically nothing -test
only exists within yourfunction (response) {}
block. It doesn't exist outside it, and as such the rest of the component can't see it.By properly setting
this.test
: (the.bind(this)
is critical here)...
test
will become available to your template, and this bit will work as it should:(Assuming
response.data
is what you expect it to be, of course.)One of the major points of using Vue is that you're never doing raw appends of HTML like you'd do in jQuery. Instead, you set data in the component, and the component adjusts its HTML automatically to fit that data.