Reputation: 4480
I am using Vue.js and Axios to make an API call. When the call returns I want to set a variable that is false to true temporarily. I am using a SetTimeout to do this. The issue I am running into is that unless I hard code the variable name Vue does not respond.
In my template
<i v-if="fnameEntered" id="fnameCheckPlacement" class="fnameCheck" class="form-control-feedback glyphicon glyphicon-ok" style="margin-right: 10%;"></i>
Then in my script
methods: {
submitFirstName: function(event){
this.updateUserInfo(this.fname, "fname", this.fnameEntered);
},
updateUserInfo: function (val, field, checkMark) {
axios.post('/userprofilepage', {
val: val,
field: field
})
.then(response => {
let self = this;
setTimeout(function() {
self.checkMark = false;
}, 2000);
this.checkMark = true;
})
.catch(error => {
console.log(error);
})
.finally(() => this.loading = false)
},
}
I am trying to pass this.fnameEntered
as the variable checkMark
into updateUserInfo. When I hard code this.fnameEntered = true
and this.fnameEntered = false
. I get the result I want.
But, when I try to use "this.checkMark" or "self.checkMark" nothing happens. What am I doing wrong.
Upvotes: 1
Views: 1774
Reputation: 1292
It is not updating because you are passing a boolean which is primitive data type. JavaScript always pass the primitive data types into function as value and not by reference. There are 2 ways you can make it work
this.fnameEntered
inside your methodthis.fnameEntered
to an object as this.fnameEntered = { value: false}
then use checkMark.value = true
inside your methodUpvotes: 1
Reputation: 7220
Naturally it's not going to work. When you pass this.fnameEntered
into the method call, you no longer hold a reference to the original property fnameEntered
, only a copy of the value it contained when you invoked the method. Furthermore, this.checkMark
and self.checkMark
will check for the hard-coded property name checkMark
, which is completely different from the variable name checkMark
.
If you want to retrieve a dynamic property name's value, you need to do the following:
1. Pass in the name of the desired property as a string.
2. Retrieve the value using the passed in property name.
This will look something like this:
methods: {
submitFirstName: function(event){
this.updateUserInfo(this.fname, "fname", "fnameEntered");
},
updateUserInfo: function (val, field, propertyName) {
axios.post('/userprofilepage', {
val: val,
field: field
})
.then(response => {
let self = this;
setTimeout(function() {
self.$data[propertyName] = false;
}, 2000);
this.$data[propertyName] = true;
})
.catch(error => {
console.log(error);
})
.finally(() => this.loading = false)
}
}
Upvotes: 1