I'm not sure if I'm doing this properly. Please have a look at this simple 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>
As you can see I'm saving the reference of this into a variable called self
because the value of this
changes in lambda functions, e.g. ajax().then((obj) => self.name = obj.data);
My problem is when this another instance of component is created, it overwrites the value of self
in previous instance. So for example if I have two <test id="1"></test>
and <test id="2"></test>
then the later component overwrites the self
variable of the first one (same happens in v-for
too).
So my question is how can I create the self
variable which saves to the value of this
for every instance and doesn't get overwritten?
Edit: Yes I know I can do self = this
inside every function but this is just a bare-bones example with 1 method. In my actual component I have 20+ functions I don't want to do self = this
in every function. Which is why I can to create a variable that I can just assign once during the create
call and use it everywhere (like we used to use that
variable).