Can you provide some guidance on my approach? Here is an example of a basic Vue component Test.vue
:
<template>
<div>
Hi from {{name}}
</div>
</template>
<script>
let self;
export default {
created: function () {
self = this;
},
methods: {
load() {
ajax().then((obj) => self.name = obj.data);
}
},
data() {
return {
name: 'one',
}
}
}
</script>
In the code snippet, I store the reference to this
in a variable called self
. This is necessary because the value of this
changes within arrow functions, like in this line:
ajax().then((obj) => self.name = obj.data);
The issue I'm facing is that when another instance of the component is created, it replaces the value of the self
variable in the previous instance. For instance, if I have two components like this: <test id="1"></test>
and <test id="2"></test>
, the second component overwrites the self
variable of the first one (similarly with v-for
).
My question is how can I ensure that the self
variable retains the value of this
for each instance without being overwritten?
Edit: I understand that I could set self = this
in every function, but this is just a simple example with one method. In reality, my component has over 20 functions, so setting self = this
in each function is not optimal. I am looking for a way to create a variable during the create
call that I can assign once and use throughout the component (similar to using a that
variable).