Shesh Narayan Deshmukh
Shesh Narayan Deshmukh

Reputation: 333

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')

Upvotes: 2

Views: 1853

Answers (1)

Kuban
Kuban

Reputation: 193

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>

Upvotes: 5

Related Questions