typescriptvue.jsionic-frameworkeslintionic5

How to resolve ESLint error in defining `this` inside nested scope in Ionic Vue method


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.


Solution

  • 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