Here is a simple example to showcase:
<template>
<div>
{{ count }}
<button @click="click">Click</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
click() {
this.count++
}
}
};
</script>
We have a data property called count and a button that increments the count when clicked.
Now, let's explore an alternative approach for some reason:
click() {
let count = this.count
count += 1
}
The idea here is to first assign the data property to a local variable, then increase the local variable count in order to trigger Vue's reactivity.
Given that Vue uses Object.defineProperty's setter for data properties, is it feasible to mimic those setters?
Could this method work as intended?
Update
I am aiming to simplify the following code snippet:
<script lang="ts">
export default {
data() {
return {
isALoading: false,
isBLoading: false
};
},
methods: {
hitAPI(type: "A" | "B") {
if (type === "A") {
this.isALoading = true;
fetch(someAPI)
.then(() => {
this.isALoading = false;
})
.catch(() => {
this.isALoading = false;
});
} else {
this.isBLoading = true;
fetch(someAPI)
.then(() => {
this.isBLoading = false;
})
.catch(() => {
this.isBLoading = false;
});
}
}
}
};
</script>