'How to call method in setup of vuejs3 app?

In vuejs3 app I retrieve data from db with axios in method, like :

<script>
  import appMixin from '@/appMixin'
  import app from './../../App.vue' // eslint-disable-line
  import axios from 'axios'

  const emitter = mitt()

  export default {
    name: 'adminCategoriesList',
    mixins: [appMixin],
    data: function () {
      return {
        categoriesPerPage: 20,
        currentPage: 1,
        categoriesTotalCount: 0,
        categories: []
      }
    },

    components: {
    },
    setup () {
      const adminCategoriesListInit = async () => {
        this.loadCategories() // ERROR HERE
      }

      function onSubmit (credentials) {
        alert(JSON.stringify(credentials, null, 2))
        console.log('this::')
        console.log(this)
        console.log('app::')
      }

      onMounted(adminCategoriesListInit)

      return {
        // schema,
        onSubmit
      }
    }, // setup

    methods: {
      loadCategories() {
        ...
      }

and I got error in browser's console :

Cannot read property 'loadCategories' of undefined

If to remove “this.” in loadCategories call I got error :

'loadCategories' is not defined

I need to make loadCategories as method, as I need to cal;l it from different places.

Which way is correct ?

Thanks!



Solution 1:[1]

You could use composition and options api in the same component but for different properties and methods, in your case the data properties could be defined inside setup hook using ref or reactive, the methods could be defined as plain js functions :

import {ref} from 'vue'
export default {
  name: 'adminCategoriesList',
  mixins: [appMixin],
  components: {
  },
  setup () {
    const categoriesPerPage= ref(20);
    const currentPage=ref(1);
    const categoriesTotalCount=ref(0),
    const categories=ref[])

    const adminCategoriesListInit = async () => {
      loadCategories()
    }

    function onSubmit (credentials) {
      alert(JSON.stringify(credentials, null, 2))
    }

    functions loadCategories(){
      ...
    }

    onMounted(adminCategoriesListInit)

    return {
      // schema,
      onSubmit,
      categoriesPerPage,
      currentPage,
      categoriesTotalCount,
      categories
    }
  },

the properties defined by ref could be used/mutated by property.value and used in template like {{property}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1