【问题标题】:How to call method in setup of vuejs3 app?如何在 vuejs3 应用程序的设置中调用方法?
【发布时间】:2021-02-21 01:07:46
【问题描述】:

在 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

如果要删除“this”。在 loadCategories 调用中 我得到了错误:

'loadCategories' is not defined

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

哪种方式正确?

谢谢!

【问题讨论】:

  • 你想从setup返回方法loadCategories。另外,我建议使用完整的 Composition API 或 Options API——但不要同时使用。
  • 我更喜欢Composition API,但以哪种方式?我现在的结构出了什么问题?
  • 好吧,尝试将方法放在setup 回调中并从那里返回。这允许您访问它以及在模板上公开它(一旦返回)。

标签: vue.js vuejs3 vue-composition-api


【解决方案1】:

您可以在同一个组件中使用组合和选项 api,但对于不同的属性和方法,在您的情况下,可以使用 refreactivesetup 挂钩内定义数据属性,方法可以定义为纯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 使用/变异,并在模板中使用,例如{{property}}

【讨论】:

  • 谢谢!请提供更多关于 ref 的详细信息,并附上描述的链接?
  • 不客气,我添加了官方文档的链接,观看video
猜你喜欢
  • 2020-11-11
  • 1970-01-01
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多