zoukankan      html  css  js  c++  java
  • 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 导入单个变量或函数时 即使是一个 也需要使用 {}

  • 相关阅读:
    第八天-2019-12-3环境变量-自动挂载-别名
    Raid
    图文并茂 RAID 技术全解 – RAID0、RAID1、RAID5、RAID100
    第七天-2019-12-2改网卡,dns,挂载
    第六天2019-11-29vi命令使用技巧与架构目录
    linux目录架构
    第五天-2019-11-28基本配置命令
    第四天--2019-11-27网络信息配置
    ue4 Widget to RenderTarget
    UE4 ProcessEvent multiple parameters
  • 原文地址:https://www.cnblogs.com/xhliang/p/11765223.html
Copyright © 2011-2022 走看看