Search code examples
vuejs3vue-composition-api

how to access a method inside onMounted in vue3 composition api?


what I am trying to do is to access a method after the setup is done and page is mounted in composition API but vue is not accessing the method

what I am doing wrong? here is my code -

export default defineComponent({  
  setup() {
    onMounted(() => {
      this.calcStartIndex();
    });
    return {};
  },
  methods: { 
    calcStartIndex() {
      console.log("startIndex");
    }
  },
})

The error I am getting -

TypeError: Cannot read properties of undefined (reading 'calcStartIndex')

Solution

  • You should declare method inside setup function

    export default defineComponent({  
      setup() {
        function calcStartIndex() {
          console.log("startIndex");
        }
    
        onMounted(() => {
          calcStartIndex();
        });
    
        return {};
      },
    })
    

    or even better with usage of script setup

    <script setup>
      function calcStartIndex() {
        console.log("startIndex");
      }
    
      onMounted(() => {
        calcStartIndex();
      });
    })
    </script>