javascript

Export multiple classes and functions in ES6 modules

77 / 100

Export multiple classes and functions in ES6 modules

 

Export Classes

my/
└── services/
    ├── Foo.js
    ├── Bar.js
    └── index.js
分別建立 class: Foo & Bar
// Foo.js
export default class Foo {
  // class definition
}

// Bar.js
export default class Bar {
  // class definition
}
index.js 將所有  class 加入後匯出
import Foo from './Foo';
import Bar from './Bar';

export {
  Foo,
  Bar,
}
在程式中使用 import {} 匯入
import {Foo, Bar} from 'my/services';

Export Functions

 建立多個 function: login & refreshToken
import axios from '../plugins/vue-axios'

const login = (data) => axios.post('/user/login', data).then((res) => res.data)
const refreshToken = (data) => axios.post('/user/refresh-token', data).then((res) => res.data)

export default {
  login,
  refreshToken
}
index.js 將 class & function 加入後匯出
// functions
import authService from './auth.service'

// classes
import UserService from './user.service'

// export classes without default
export {
  authService,
  UserService
}
在程式中使用 import {} 匯入
# function 範例
import { authService } from '../../services'

const login = ({ commit }, { username, password }) => {
  const data = {
    username: username,
    password: password
  }  

  authService.login( data )
    .then( (auth) => {  
      commit('loginSuccess', auth)      
      store.dispatch('app/showSuccess', i18n.t('common.loginSuccess') )
      router.push('/')
    })
    .catch((error) => {      
      commit('loginFailure')
      store.dispatch('app/showError', { error : { message: i18n.t('common.loginFailure') } } )
    })
}

# class 範例
import { UserService } from '../../services'

export default {
  userService = null ,
  created() {
    this.userService = new UserService()
  },
  mounted() {
    this.userService.getUserList().then((data) => this.users = data )
  }
}

參考:

https://stackoverflow.com/questions/38340500/export-multiple-classes-in-es6-modules

https://stackoverflow.com/questions/33178843/es6-export-default-with-multiple-functions-referring-to-each-other