首页 > 解决方案 > 如何在 vuejs3 应用程序的设置中调用方法?

问题描述

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

<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 作为方法,因为我需要从不同的地方调用它。

哪种方式是正确的?

谢谢!

标签: vue.jsvuejs3vue-composition-api

解决方案


您可以在同一个组件中使用组合和选项 api,但对于不同的属性和方法,在您的情况下,可以使用或在setup钩子中定义数据属性,这些方法可以定义为普通的 js 函数:refreactive

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在模板中使用/变异和使用,例如{{property}}


推荐阅读