access state in setup on methods Vue 3 got error TS doesn't exist

I am using Vue 3 and TS, I have some states in the Setup function which like this

export default defineComponent({
  setup() {
    const isLoadingSendData = ref(false)

    return { isLoadingSendData }
  
  },
  methods: {
    disableBtn(): boolean {
       // on Webstorm i got error: TS2339: Property 'isLoadingSendData' doesn't exist 
       // on type 'disableBtn(): boolean'
       if(this.isLoadingSendData) {
         return // do something
       }
       return // do something
    }

  }
})

that is just an example I can give for a case, the this.isLoadingSendData got error red on my IDE, does anyone know why ??


Solution 1:

You can't call composition api setup() variables in options api methods, data, etc,if you want to declare a method inside composition api, it's like this:

export default defineComponent({
  setup() {
    const isLoadingSendData = ref(false);
    const disableBtn = (): boolean => {
      if (this.isLoadingSendData.value) {
        return; // do something
      }
      return; // do something
    };

    return { isLoadingSendData, disableBtn };
  }
});

If you want to use options api, you can declare it like this:

export default defineComponent({
  data() {
    return {
      isLoadingSendData: false
    };
  },
  methods: {
    disableBtn(): boolean {
      if (this.isLoadingSendData) {
        return; // do something
      }
      return; // do something
    }
  }
});

so the choice is either you use composition api or options api.

Also, there is alternative syntax for composition api, that is to use <script setup> tag. You can declare it like this:

<script setup lang="ts">
import { ref } from "vue";

const isLoadingSendData = ref(false);
const disableBtn = (): boolean => {
  if (this.isLoadingSendData.value) {
    return; // do something
  }
  return; // do something
};
</script>

you can access everything inside <script setup> tag in template tag