How can I assign data from received data?
my code is below. axios is working well. I can get response.data from server . and I tried to assign the data to imglists variable. but It doesn't assign. What's wrong with me? Is There something wrong?
please help me out.
var app = new Vue({
el: '#app',
data: {
imglists: [],
},
created(){
axios.post('https://test.com/hello-lambda')
.then(function (response) {
this.imglists = response.data;
}).catch(function (error) {
console.log(error);
});
}})
In the example code above this is bound to the created function. To bind this to the object context, you'll need a function that doesn't bind this. Use ES6(ES2015) to solve the binding issue.
Use the ES6 syntax:
var app = new Vue({
el: '#app',
data: {
imglists: [],
},
created(){
axios.post('https://test.com/hello-lambda')
.then(response => this.imglists = response.data)
.catch(error =>console.log(error));
}
})
Your reference to this is scoped to the function it is inside of so you need to create an external reference.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Also data should be a returned object to create a reactive object to trigger re-renders (nextTick) when the data is changed in imagelists due to this usage case being an asynchronous call.
https://v2.vuejs.org/v2/guide/reactivity.html#Async-Update-Queue
var app = new Vue({
el: '#app',
data: () => ({
imglists: []
}),
created(){
let self = this;
axios.post('https://test.com/hello-lambda').then(response => {
self.imglists = response.data;
}).catch(error => {
console.log(error);
});
}})
The var self and function then() plus its own content is scoped to function created() allowing child functions access to vars declared at the top level (parent function or script file) but be mindful if 'strict mode' is enforced as this will change the behavior of scoping / inheritance.
Related
This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 1 year ago.
I cannot for the life of me figure this out. I have what seems like a super simple block of code, instantiating a new Vue object hooked to a div with id providers.
const app = new Vue({
el: '#providers',
data: {
providers: []
},
created: () => {
console.log(this);
},
})
For some reason, when I call console.log(this) in created, it's returning "Window {window: Window, self: Window, document: document, name: "", location: Location, …}"
I'm running Vue 2.6.12. Can anyone help me resolve this issue?
I can't access any of my data in my lifecycle commands because of this.
I think the problem is in the arrow function =>: it does not have its own bindings to this or super, and should not be used as methods (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
To bind this to a method use function long or short notation.
Long notation:
const app = new Vue({
el: '#providers',
data: {
providers: []
},
created: function () {
console.log(this);
},
})
Short notation:
const app = new Vue({
el: '#providers',
data: {
providers: []
},
created() {
console.log(this);
},
})
I have a Vue.js 3 app. In this app, I'm trying to search through an array of object. I've created a fiddle here. In this fiddle, the code causing the issue looks like this:
async runSearch() {
let searchResults = this.data;
if (this.searchQuery) {
let info = JSON.stringify(searchIndex);
alert(info);
console.log(searchIndex);
searchResults = await courseIndex.search(courses);
}
this.results = searchResults;
}
For some reason, it's like searchIndex doesn't exist. However, I do have it in the model as shown here:
data() {
return {
searchIndex: null,
searchQuery: null,
data: data,
results: null,
}
}
What am I doing wrong? Why can't I execute a search?
use this.searchIndex to access reactive variables defined in data in Vue.
I am making simple ajax call with vuejs and axios:
var app1 = new Vue({
el: '#app1',
data: {
test: []
},
methods: {
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
}
});
Why is this working:
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
But this is not working, changes are not mapped into table (this.test is undefined):
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
}
This is because of the way arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
When using an arrow function, this is implicitly bound to this of the enclosing scope, which is, in your case, the vue instance on which the method is called.
So you're setting the data of your view model, which works.
When using a std. function, there is no this in the scope, hence the error. To use a std. function, you need to define a closure for your view model like this:
setAJAX: function () {
let vm = this
axios.get('...').then( function(response) {
vm.test = response.data.listBACAET
});
}
I wrote the following code and Vue complains:
[Vue warn]: Property or method "incidents" is not defined on the
instance but referenced during render. Make sure to declare reactive
data properties in the data option.
I don't see why incidents cannot be accessed?
var app = new Vue({
el: '#app',
data: {
responders: [],
incidents: []
},
mounted: function () {
this.getIncidents();
},
methods: {
getIncidents: function() {
console.log('getIncidents');
var app = this;
this.$http.get('/api/v1/incidents').then(function(response) {
// set data
var incidentsReceived = response.data.map(function (incident) {
return incident;
});
Vue.set(app, 'incidents', incidentsReceived);
})
},
getResponders: function() {
console.log('fetchResponders');
var app = this;
this.$http.get('/api/v1/responders').then(function(response) {
// set data on vm
var respondersReceived = response.data.map(function (responder) {
return responder
});
Vue.set(app, 'responders', respondersReceived);
});
}
}
})
EDIT: Didn't read the code very well for the first time. Verify that you have data inside the response and if not don't set it the incidents array.
data is meant for internal component data modeling, while props, which can be assigned externally, are defined using the props key for your component.
In other words, try:
var app = new Vue({
...,
props: {
incidents: {
type: Array,
required: false //change this as you see fit.
}
},
...
});
For full documentation on component properties, please refer to the official guide.
I'm using a v-for loop with data fetched from JSON file. Is there a way to re-render the DOM and whole v-for loop after loading a new JSON file and replacing the old one?
What I'm trying to achieve is load different sets of products on click and update DOM.
Vue.use(VueResource);
var productsList = new Vue({
el: '#vue',
data: function () {
return {
products: []
};
},
ready: function () {
this.$http.get('data/data.json').then(function (response) {
this.products = response.data;
});
},
methods: {
loadProducts: function (url) {
this.$http.get(url).then(function (response) {
this.products = response.data;
});
}
}
});
The code above should be sufficient for updating your DOM automatically. There are 2 errors however and 1 thing you should consider.
Anonymous functions have different scopes in javascript. This means that when you have an anonymous function function(response) then you lose the scope of the vue instance this. In order to deal with such situations you have to either use arrow functions if you have support for them in your project or save this into another variable before entering the anonymous function.
Vue.use(VueResource);
var productsList = new Vue({
el: '#vue',
data: function () {
return {
products: []
};
},
ready: function () {
var self=this;
this.$http.get('data/data.json').then(function (response) {
self.products = response.data;
});
},
methods: {
loadProducts: function (url) {
var self=this;
this.$http.get(url).then(function (response) {
self.products = response.data;
});
}
}
});
Also if you have this exact code, you should've received an error in browser with products being undefined.
Once you update the products data it will automatically change the DOM as par the latest data, as vue data is reactive. One error I see in your code is, you may have wrong this inside the this.$http block. instead of using function() syntax, use arrow function, which does not bind it's own this, arguments, super, or new.target, like following:
Vue.use(VueResource);
var productsList = new Vue({
el: '#vue',
data: function () {
return {
products: []
};
},
ready: function () {
this.$http.get('data/data.json').then((response) => {
this.products = response.data;
});
},
methods: {
loadProducts: function (url) {
this.$http.get(url).then( (response) => {
this.products = response.data;
});
}
}
});