Vue.js使用方法合并2个文件

问题描述 投票:1回答:1

我有一个api与不同主题的路线,所以我想尽可能保持我的api电话干净。我尝试从1个导入导入2个不同文件中的所有vue方法。

我尝试做但不工作的是如下;我创建了两个使用vue方法进行api调用的文件:categories.js和expenses.js,我创建了一个将这些文件一起导入的index.js文件。所以在我的主文件上我导入了index.js文件,所以我可以使用expense.js和categories.js文件中的方法

我得到以下内容:TypeError:this.getCategories不是一个函数

categories.vue

import * as API from '@/api'

export default {
    mixins: [API],
    mounted(){
        this.getCategories()
    }
}

index.js

import * as Categories  from './categories.js'
import * as Expenses    from './expenses.js'

export default {
    Categories,
    Expenses
}

categories.js

export default {
    methods: {
        getCategories(){
            this.$http.get('api.example.com')
                .then(response => {
                    //  response
                })
        }
    }
}

expenses.js

export default {
    methods: {
        getExpenses(){
            this.$http.get('api.example.com')
                .then(response => {
                    //  response
                })
        }
    }
}
javascript vue.js
1个回答
1
投票

更改index.js以导出数组:

import Categories  from './categories.js'
import Expenses    from './expenses.js'

export default [
  Categories,
  Expenses
]

然后将类别组件更改为:

import API from '@/api'

export default {
  mixins: API, // [...API, others, more] if using more mixins.
  mounted(){
    this.getCategories()
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.