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 導入單個變量或函數時 即使是一個 也需要使用 {}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM