This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
i have started working on a small project using VueJs, i've made a get request using Axios library which returns some data as expected, but I cannot call loadUsers function using this inside mounted
this is my code:
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then(function(data){
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
as you can see also i've used self variable to call my loadUsers() function, but i'm still getting
this is undefined error
You're referencing this.users within the callback to axios.get().then() in loadUsers(). Due to you're using a standard function and not an arrow function, this is not referring to the Vue instance, i.e. the scope for this is now incorrect. Either use an arrow function or change the reference:
// Do this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then((data) => { // Using an arrow function.
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
// Or this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
let self=this; // Adding "self"
axios.get('/Thirdparty/loadUsers').then(function(data){
self.users = data.data; // Referencing "self" instead of "this".
});
}
},
created(){
let self=this
self.loadUsers();
}
}
Related
function HeaderreRender() {
HeaderRender = false;
this.$nextTick(() => {
HeaderRender = true;
});
};
export default {
name: 'Home',
components: {
HeaderItem,
},
data: function() {
return {
HeaderRender: true,
};
}
}
this is the code now I want to use v-if="HeaderRender" to re-render the headerItem
but when I call function HeaderreRender()
it is replying to me
Uncaught ReferenceError: HeaderRender is not defined
on the function
any suggestions? on why this happens?
Try to place the HeadereRender() function within the methods object of the component and also, it's this.HeaderRender=true
In simple terms, this method does not know about the HeaderRender variable, thus it is not defined in the scope of the function, written that way
This question already has answers here:
How to call another function within the same object?
(2 answers)
Closed 4 years ago.
i want to call the isAuthenticated() method within the logout function.
(Im not sure what you call this layout its like a variable object containing functions)
var svc = {
logout: function () {
isAuthenticated() // Call isAuthenticated function here
},
login: function () {},
isAuthenticated: function () {}
}
Simply calling isAuthenticated() does not work.
svc is an object, where are logout & isAuthenticated are methods.You can use this to call the function.Here this points to the svc object
var svc = {
logout: function() {
this.isAuthenticated() // Call isAuthenticated function here
},
login: function() {
},
isAuthenticated: function() {
console.log('isAuthenticated called');
}
}
svc.logout()
Add this to it.
var svc = {
logout: function () {
this.isAuthenticated() // Call isAuthenticated function here
},
login: function (){
},
isAuthenticated: function () {
console.log("Test");
}
}
svc.logout();
I believe what you are looking for is:
this.isAuthenticated();
You need to use "this" to call other members of the same object.
Javascript object variables and functions are accessed by prefixing the object name followed by the variable/function name.
In your case, you can call isAuthenticated() like this:
svc.isAuthenticated()
You nee to use the reference of that object svc --> this.isAuthenticated()
var svc = {
logout: function() {
this.isAuthenticated()
},
login: function() {},
isAuthenticated: function() {
console.log("Is Authenticated!?")
}
}
svc.logout();
Another alternative is creating a function and declaring a variable, this way you will be able to call it directly as follow:
var svc = function() {
var isAuthenticated = function() {
console.log("Is Authenticated!?");
}
this.isAuthenticated = isAuthenticated;
this.logout = function() {
isAuthenticated()
};
this.login = function() {};
}
new svc().logout();
new svc().isAuthenticated();
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I have the following but I get error Cannot read property 'push' of undefined:
var vm = new Vue({
el: '#root',
data: {
posts: [],
newPost: {}
},
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
})
}
});
In my network tab in chrome dev tools I can see response.data is clearly an object:
{
"id": 131,
"postContent": "<p>test</p>\n",
}
So why I'm i getting this error?
That's because this context is assigned incorrectly which means that this does not point on the Vue component. To solve this problem, you can use => syntax which simply means a sophisticated way of this self = this outside of the target callback.
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
As IzumiSy said, this very common problem when using axios or even setTimeout function. You can use es6 arrow synax, create temporary local variable with vm or bind it to the function.
ES6
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
Temporary variable
createPost: function() {
let vm = this;
axios.post("api/posts/create", this.newPost).then(function (response) {
vm.posts.push(response.data);
})
}
Binding
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
}.bind(this))
}
I'm writing a component for Vue.js and I need to modify data on event. But for some reason, when I access it, it's set as undefined
module.exports = {
data: function() {
return {
visible: true
}
},
mounted: function() {
this.eventHub.$on('minimize', function(window_id) {
console.log(this.visible);
this.visible = !this.visible;
});
},
props: ["windowId"]
}
When the event is called for the first time, data.visible is undefined, for some reason.
Is there anything I'm doing wrong?
Thanks!
Because function (window_id) has it's own scope, you can not access this.
This can be solved by adding self = this.
let self = this
this.eventHub.$on('minimize', function(window_id) {
console.log(self.visible);
self.visible = !self.visible;
});
As Nick Rucci pointed out, you can also use an arrow function, and get rid of self = this.
this.eventHub.$on('minimize', (window_id) => {
console.log(this.visible);
this.visible = !this.visible;
});
I'm using ES6 with Angular JS 1.X. Whenever I try to access a class-level variable (declared in the constructor) in a $resource.query callback function, I get this error:
"TypeError: Cannot read property 'maxSize' of undefined".
eg:
Constructor:
constructor() {
this.invArr = [];
this.maxSize = 3;
}
Class Method:
bindData(){
this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
rtbProductNbr: this.productNumber
}, function (data) {
if (angular.isDefined(data)) {
this.invArr = data; //this.invArr not found
console.log(this.maxSize); //this.MaxSize not found.
}
});
}
The context of this has changed in the callback function for this.invLookUpSvc.getPortalInvByProdNbrSum().query. To resolve this, you should bind the callback function to the this context:
bindData(){
this.invArr = this.invLookUpSvc.getPortalInvByProdNbrSum().query({
rtbProductNbr: this.productNumber
}, function (data) {
if (angular.isDefined(data)) {
this.invArr = data;
console.log(this.maxSize);
}
}.bind(this));
}