• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

凉梁凉糕

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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 导入单个变量或函数时 即使是一个 也需要使用 {}

posted on 2019-10-30 15:32  凉梁凉糕  阅读(7575)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3