简体   繁体   English

如何导出多个函数 ES6

[英]How to export multiple functions ES6

I'm working in a vue project, I'm very new to vue.我在一个 vue 项目中工作,我对 vue 很陌生。

We have a db_handler.js in out /src/utility folder.我们在 /src/utility 文件夹中有一个 db_handler.js。 It looks like this:它看起来像这样:

import fakeApiCall from "./mock";
import axios from "axios";
import { DEBUG_MODE, API_ENDPOINT } from "./namespaces";

function fetchData(method, slug, payload) {
  //axios.defaults.headers.withCredentials = true;
  //return (!DEBUG_MODE) ? axios[method](`${API_ENDPOINT}${slug}`, payload) : fakeApiCall(slug);
  return axios[method](`${API_ENDPOINT}${slug}`, payload);

  /*var url = "http://localhost:8080" + slug

  return axios({
    method: method,
    url: url,
    headers: {
        'Authorization': payload
    }
  });*/
}

function sendData(method, slug, payload) {
  axios[method](`${API_ENDPOINT}${slug}`, payload);
}

export default fetchData

What I need to know: How can I export my sendData() ?我需要知道的是:如何导出我的sendData() They used a short syntax so far because they only exported one function. How can I export multiple functions?到目前为止,他们使用了一个简短的语法,因为他们只导出了一个 function。如何导出多个函数? I also want the names to remain "fetchData" and "sendData"我还希望名称保留为“fetchData”和“sendData”

EDIT: I tried to apply the approaches of Iamhuynq and Bergi, but now something goes south.编辑:我尝试应用 Iamhuynq 和 Bergi 的方法,但现在有些事情向南。 I am importing the functions first and foremost in moduleUser.js and authUser.js which reside in /src/store/modules .我首先导入位于/src/store/modules中的moduleUser.jsauthUser.js中的函数。 The authUser.js is used for the identification of the user, so of course it is used in the login screen. authUser.js用于用户的识别,所以它当然用于登录屏幕。 When I now try to login, I get "Type Error: Object undefined".当我现在尝试登录时,出现“类型错误:Object 未定义”。 I guess this is because the functions returning the server response are somehow failing or not found.我猜这是因为返回服务器响应的函数不知何故失败或找不到。

The codebase connected to this behavior is the Login screen, the db_handler which Ive already shown you and a module called "moduleAuth.js".与此行为相关的代码库是登录屏幕、我已经向您展示的 db_handler 和一个名为“moduleAuth.js”的模块。

First, the login screen looks like this:首先,登录屏幕如下所示:

<template>
  <div>
    <h1>Login</h1>
    <p>Name:</p>
    <div class="inputbox">
      <input ref="username" type='text' v-on:keydown.enter="userLogin">
    </div>
    <p>Password:</p>
    <div class="inputbox">
      <input class="inputbox" ref="password" type='password' v-on:keydown.enter="userLogin">
    </div>
    <p>{{error}}</p>
    <button v-on:click='userLogin'>Login</button>
  </div>
</template>

<script>
import store from "../store/store";

import { AUTH_REQUEST } from "../store/actions/auth";

export default {
  data () {
    return {
      error: ""
    }
  },
  methods: {
    userLogin: function(){
      this.error = '';
      store.dispatch(AUTH_REQUEST,{username: this.$refs.username.value, password: this.$refs.password.value})
      .then((res) => {
        this.$router.push({path: '/profile'});
      })
      .catch((err) => {
        this.error = err;
      });
      this.$refs.password.value = '';
    }
  }
}
</script>

<style>
.inputbox{
  width: 25%;
}
</style>

moduleAuth.js , from which the AUTH_REQUEST vue-action is coming, looks like this: moduleAuth.js vue-action 来自AUTH_REQUEST ,看起来像这样:

import axios from "axios";
import Vue from 'vue';
import Vuex from 'vuex';
import {fetchData, sendData} from "../../utility/db_handler";

import { USER_REQUEST } from "../actions/user";
import { AUTH_REQUEST, AUTH_LOGOUT, AUTH_FAIL, AUTH_SUCCESS } from "../actions/auth";
import { METHOD_POST, JWT } from "../../utility/namespaces";

Vue.use(Vuex);

const storeAuth = {
  state: {
    token: localStorage.getItem(JWT) || '',
    loginState: ''
  },
  getters: {
    isAuthenticated: state => !!state.token,
    getLoginState: state => state.loginState
  },
  mutations: {
    [AUTH_REQUEST]: (state) => {
      state.loginState = 'pending';
    },
    [AUTH_FAIL]: (state) => {
      state.loginState = 'error';
    },
    [AUTH_SUCCESS]: (state, mToken) => {
      state.loginState = '';
      state.token = mToken;
    },
    [AUTH_LOGOUT]: (state) => {
      return new Promise ((resolve, reject) =>{
        state.loginState = '';
        state.token = '';
        localStorage.removeItem(JWT);
        resolve();
        //Catch?
      })
    }
  },
  actions: {
    [AUTH_REQUEST]: ({ commit, dispatch }, uObj) => {
      return new Promise((resolve, reject) => {
        commit(AUTH_REQUEST);
        fetchData(METHOD_POST, '/login',{
            username: uObj.username,
            password: uObj.password
          }).then(function (res) {
          commit(AUTH_SUCCESS,res.headers.authorization);
          localStorage.setItem(JWT,res.headers.authorization);
          axios.defaults.headers.common['Authorization'] = res.headers.authorization;
          dispatch(USER_REQUEST);
          resolve(res.data);
        }).catch(function(err) {
          commit(AUTH_FAIL);
          reject(err);
        })
      })
    },
    [AUTH_LOGOUT]: ({ commit}) => {
      commit(AUTH_LOGOUT);
    }
  }
}

export default storeAuth

Now, if just roll back the changes to the export/import sections, everything works.现在,如果只是回滚对导出/导入部分的更改,一切正常。 So the problem should definitely be connected to this.所以问题肯定与此有关。

you can use export你可以使用export

export function sendData() {...}

and you can import like this你可以像这样导入

import fetchData, { sendData } from '/src/utility/db_handler.js;'

Here my suggestion is, if you are exporting more then one function, you should use export method instead of export default.我的建议是,如果您要导出多个函数,则应使用导出方法而不是导出默认值。 It will make your code more readable and ll use for future debugging.它将使您的代码更具可读性,并将用于将来的调试。

export function function1(params) {
 .......
}

export function function2() {
 ......
}

Here there is a two way to import functions这里有两种导入函数的方式

  1. by using import { function1, function2} from "./exportedFunctionFile" make sure you are using same function name as you exported!通过使用import { function1, function2} from "./exportedFunctionFile"确保您使用的函数名称与导出的函数名称相同!
  2. other method is use * as yourVariableName example import * as myFunctions from "./exportedFunctionFile" this would use when you are exporting too many functions now you can use your imported functions as myfunctions.function1()其他方法是使用* as yourVariableName示例import * as myFunctions from "./exportedFunctionFile"这将在您导出太多函数时使用,现在您可以将导入的函数用作myfunctions.function1()

if you want to export using default key word, export functions as object example export default {function1,function2} and you could use it like import * as myFunctions from "./exportedFunctionFile" which is similar as a second way of importion.如果您想使用默认关键字导出,导出函数作为对象示例export default {function1,function2}并且您可以像import * as myFunctions from "./exportedFunctionFile"一样使用它,这类似于第二种导入方式。

Hope it will Help you希望它会帮助你

export the functions in an object导出对象中的函数

export default {
    sendData: sendData,
    fetchData: fetchData
}

then to use然后使用

import * as DBHandler from '@/src/utility/db_handler'
...
DBHandler.sendData()

On the function files关于 function 文件

func1(params) {
...
}

func2(params) {
...
}

export default default {
    function1: function1,
    function2: function2
}

On the other file在另一个文件上

import * as _ from './module address'

then然后

_.default.func1.call(args)
_.default.func2.call(args)

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

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