如何在 vuejs3 应用程序的设置中调用方法?

How to call method in setup of vuejs3 app?

在 vuejs3 应用程序中,我使用 axios 方法从数据库中检索数据,例如:

<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() {
        ...
      }

我在浏览器的控制台中遇到错误:

Cannot read property 'loadCategories' of undefined

如果删除“这个”。在 loadCategories 调用中 我收到错误:

'loadCategories' is not defined

我需要将 loadCategories 作为方法,因为我需要从不同的地方调用它。

哪种方式正确?

谢谢!

您可以在同一组件中使用组合和选项 api,但对于不同的属性和方法,在您的情况下,可以使用 ref or reactivesetup 挂钩中定义数据属性,这些方法可以定义为纯 js 函数:

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
    }
  },

ref 定义的属性可以由 property.value used/mutated 并在模板中使用,例如 {{property}}