简体   繁体   English

如何将函数导入 Vue 组件?

[英]How to import a function into a Vue component?

I have a js file named axios.js.我有一个名为 axios.js 的 js 文件。 Inside this file:在这个文件中:

import axios from 'axios';

export function axiosGet (url, data, loading) { 
        axios.get(url, data, loading)
                .then((response) => {
                    loading = false;
                    data = response.data;
                })
                .catch(error => console.log(error))
                .finally(() => {
                    loading = true;
                })
}

I have a Vue component where I import this function:我有一个 Vue 组件,我在其中导入了这个函数:

import {axiosGet} from '../axios.js'

mounted() {
        axiosGet('https://jsonplaceholder.typicode.com/users', this.APIusers, this.isLoading);
}

where APIusers and isLoading are in data.其中 APIusers 和 isLoading 在数据中。

I get no error but it's not working.我没有收到错误,但它不起作用。

What should I change to make it work?我应该改变什么才能使它工作?

Your problem is not related to importing function in vue component.您的问题与 vue 组件中的导入功能无关。

You have to change calling api function to this:您必须将调用 api 函数更改为:

  async mounted() {
    this.isLoading = true;
    const res = await axiosGet("https://jsonplaceholder.typicode.com/users");
    if (res) {
      this.APIusers = res;
    }
    this.isLoading = false;
  }

and api function:和api函数:

export async function axiosGet(url) {
  try {
    const response = await axios.get(url);
    return response.data;
  } catch (err) {
    console.log(err);
  }
}

here is working deme: https://codesandbox.io/s/hopeful-murdock-xqpws这是工作deme: https ://codesandbox.io/s/hopeful-murdock-xqpws

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM