javascript 导入其他文件的的变量 或函数

一般情况下 我们会有一个公共文件存放一些公共变量,但是变量可能在某个模块中使用 ,而在另一个模块中不想载入,如何去导入一个文件中的部分变量呢

首先 定义一个公有文件 common.js

const countryOptions = ['AM', 'CN']
const nameOptions = [
  { label: 'me', key: 'ME' },
  { label: 'your', key: 'YOUR' },
  { label: 'her', key: 'HER' }
]
const ageOptions = [
  { label: '17岁', key: '17' },
  { label: '18岁', key: '18' }
]
function getList(data) {
  return [{a:1,b:2}]
}
function publicFilter(ele) {
  if(ele){
    return '有效'
  }else{
    return '无效'
  }
}

export {
  countryOptions,
  nameOptions,
  ageOptions,
  getList,
  publicFilter
}

在需要引入的文件中可以部分的导入 也可以全部的导入

//导入单个函数 
import { getList } from '@/utils/common.js'
console.log('getName', getList())

// 导入单个变量
import { ageOptions } from '@/utils/common.js'
console.log('ageOptions', ageOptions)

//导入多个变量 (函数也是相同的)
import { countryOptions, nameOptions} from '@/utils/common.js'
console.log('countryOptions', countryOptions)
console.log('nameOptions', nameOptions)

//导入common文件中的全部内容
import * as commonSource from '@/utils/common.js'
console.log(commonSource)
console.log(commonSource.ageOptions)

注意: 1 在commonjs里面使用export将内容导出

            2 导入单个变量或函数时 即使是一个 也需要使用 {}

原文地址:https://www.cnblogs.com/xhliang/p/11765223.html