首页 > 解决方案 > 从 VUE 组件调用 typeScript 函数

问题描述

我刚开始使用 VUE,我被卡住了。

我有一个简单的 VUE 组件,它的脚本部分是:

<script>
import Dish from './dish.vue'
import SearchBar from './search.vue'
import axios from 'axios'

export default {
    components: {Dish, SearchBar},
    name: "selectDish",
    data() {
        return {
            dishes : []
        }
    },
    mounted(){     
    axios.get('http://example.com/',{method :'GET'})
    .then(response =>{
        console.log(response);
        this.dishes=response.data
        })
    }
}

我想要实现的是删除axios API GET我在上面的 VUE 组件中的调用,而是调用我在 APIService.TS 文件中编写的函数,最终进行GET调用。

我的 apiService.ts 文件如下:

import Promise, { config, resolve, reject } from 'bluebird';
import Config from '../config';
import axios from 'axios';

export class APIService{
    constructor(){  }
    public giveMeAllDishes(dishType, query) : Promise<string>{

          return new Promise((resolve,reject) =>{
               axios.get('http://example.com',{method : 'GET'})
               .then(function(respone){
                   console.log(respone);
                   resolve(respone.data);
               })
               .catch(function(err){
                   reject(err);
               })
           })
    }
}

当我将import APIService from '../../services/apiService'VUE 组件放入内部时,我收到一条错误消息:

ERROR in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/selectDish/selectDish.vue
Module not found: Error: Can't resolve '../../services/apiService'

另外,当我解决这个引用问题时,如何调用 API 服务的“giveMeAllDishes”函数VUE Component

标签: vue.jsvuejs2vue-component

解决方案


您的导入略有错误。这是它需要的:

import { APIService } from '../../services/apiService'

推荐阅读