Reputation: 5986
I have an Ionic Vue app which uses the slides
component to modify a reactive property each time it transitions. The pertinent code is like this:
<script lang="ts">
import { IonPage, IonContent, IonSlides, IonSlide,} from '@ionic/vue'
export default {
name: 'Splash',
components: { IonPage, IonContent, IonSlides, IonSlide,},
data() {
return {
contentClass: 'bg-gradient-1',
}
},
setup() {
const slideOpts = {
autoplay: {
delay: 4000,
},
}
return { slideOpts }
},
methods: {
slideChange({ target }) {
const vm = this
target.getActiveIndex().then((i) => {
vm.contentClass = 'bg-gradient-' + i
})
},
},
}
</script>
This generates the following error:
Unexpected aliasing of 'this' to local variable @typescript-eslint/no-this-alias
The reason I'm using const vm = this
is because once inside the getActiveIndex
method, the scope of this
changes and I can't modify the contentClass
data property.
Rather than just blindly disabling the ESLint rule to allow this
to be assigned to a constant I wondered if anyone was able to offer a better/proper solution?
Many thanks.
Upvotes: 9
Views: 10852
Reputation: 190
When using an arrow function, 'this' refers to the surrounding context. So no need to do that anymore!
element.addEventListener('click', () => {
console.log(this); // 'this' refers to the surrounding context
});
Upvotes: 0
Reputation: 33345
It may also be solved by not using data
and going all-in with the setup
approach:
<script lang="ts">
import { IonPage, IonContent, IonSlides, IonSlide,} from '@ionic/vue'
export default {
name: 'Splash',
components: { IonPage, IonContent, IonSlides, IonSlide,},
setup() {
const contentClass = ref<any>('bg-gradient-1');
const slideChange = ({ target }) => {
target.getActiveIndex().then((i) => {
contentClass.value = 'bg-gradient-' + i
})
},
const slideOpts = {
autoplay: {
delay: 4000,
},
}
return { slideOpts, contentClass, slideChange }
}
}
</script>
Upvotes: 3
Reputation: 2445
In .eslintrc
file on rules key add "@typescript-eslint/no-this-alias": 0
, for example in my case:
"rules": {
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-this-alias": 0,
"no-console": 1, // Means warning
"prettier/prettier": 2 // Means error
}
Upvotes: 0
Reputation: 4684
yes there is one solution. You can add the following object in your ESlint config file
{
"@typescript-eslint/no-this-alias": [
"error",
{
"allowDestructuring": true, // Allow `const { props, state } = this`; false by default
"allowedNames": ["vm"] // Allow `const vm= this`; `[]` by default
}
]
}
for more info also check on TSLint: no-this-assignment
Upvotes: 9