Vue:export import 导入导出的区别

在学习Vue时,对各种JS模块的导入与导出的方式感到困惑,简单总结如下:

一、导出与导入方式
方式1:
  1. 导出:JS中使用export default {需要导出的模块名}
  2. 导入:
    • HTML中在script标签中使用import 自定义总模块名称 from JS文件位置
    • script标签必须增加type="module"来声明这个脚本是一个模块,否则会报错。

test.js中代码:

let helloWorld=function () {
  console.log("Hello Vue");
}
let test= function () {
  console.log("test Vue ");
}
let name = 'Vue'

export default {
  helloWorld, //需要导出的模块1
  test, //需要导出的模块2
  name //需要导出的模块3
}

test.html代码:

  <script type="module"> 
    import justNameIt from './module.js' //justNameIt为自定义名称
    console.log(justNameIt.name) //Vue
    justNameIt.helloWorld() //Hello Vue
  </script>
方式2:
  1. 导出:JS中使用export 模块名
  2. 导入:
    • HTML中在script标签中使用import {模块1,模拟2...} from JS文件位置
    • script标签必须增加type="module"来声明这个脚本是一个模块,否则会报错。

test.js中代码:

export function helloWorld() {
  console.log("Hello Vue");
}
export function test() {
  console.log("test Vue ");
}
export let name = "Vue"

test.html代码:

   <script type="module">
     import { helloWorld, test, name } from './module.js'
    helloWorld() //Hello Vue
    test() //test Vue 
    console.log(name) //Vue
  </script>
二、避免模块命名冲突:

对导出的模块进行重命名import { helloWold as 新名称} from JS文件位置

总结:两者使用上几无差别, 方式1倾向全部导出,方向2倾向按需部分导出
参考: JavaScript modules 模块

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值