微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue.js-ES6模块化

1.1 export基本使用

export指令用于导出变量

export let name = 'kobe';
export let age = 18;
export let flag = true;

上面的代码还有另外一种写法

let name = 'kobe';
let age = 18;
let flag = true;
export {name, age, flag}

导出函数或类

function test(num){
    console.log(num);
}
class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    
    run(){
        console.log(this.name + '在学习');
    }
}

export{test, Person}

export default

一个模块中包含某个的功能,并不希望给这个功能命名,而且让导入者可以自己来命名。

// info1.js
export default function(){
    console.log('default function');
}

来到main.js中,这样使用就可以了

import function from './info1.js'

需要注意

export default在同一个模块中,不允许同时存在多个。

1.2 import基本使用

使用export指令导出了模块对外提供的接口,下面我们就可以通过import命令来加载对应的这个模块了

首先,我们需要在HTML代码中引入两个js文件,并且类型需要设置为module。

<script src="info2.js" type="module"></script>
<script src="main.js" type="module"></script>

import指令用于导入模块中的内容,比如main.js的代码

import {name, age, flag} from "./info1.js"
console.log(name, age, flag);

1.3 代码示例

info1.js

// 定义变量
let name = 'kobe';
let age = 18;
let flag = true;

// 定义函数
function sum(num1, num2) {
  return num1 + num2
}

// 条件判断
if (flag){
  console.log(sum(20, 30));
}

// 1.导出模块方式
export {
  flag, sum,
}

// 2.导出方式2
export let num1 = 100;
export let height = 1.71

// 3.导出函数/类
export function mul(num1, num2) {
  return num1 * num2
}

export class Person {
  run(){
    console.log('python是最优雅的语言!!!');
  }
}

// 5.export default
const address = '广东省广州市'
export default address

info2.js

// 导入模块
import {sum} from './info1.js'
// 定义变量
let name = 'Curry';
let flag = false;

console.log(sum(100, 200));

// 3.导入 export的function/class
import {mul, Person} from "./info1.js";
console.log(mul(30, 50));

main.js

// 1.导入的{}中定义变量
import {flag, sum} from "./info1.js";

// 条件判断
if(flag){
  console.log('kobe是mvp');
  console.log(sum(20, 30));
}

// 2.直接导入export定义的变量
import {num1, height} from "./info1.js";

// 3.导入函数和类对象
import {mul, Person} from "./info1.js";
console.log(mul(30,50));

const p = new Person();
p.run();

// 4.导入export default中的内容
import address from "./info1.js";
console.log(address);

// 5.统一全部导入
import * as A from './info1.js'
// 打印结果
console.log(A.flag);
console.log(A.height);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <Meta charset="UTF-8">
  <title>前端模块化</title>
</head>
<body>
  <!--引入js文件-->
  <script src="info1.js" type="module"></script>
  <script src="info2.js" type="module"></script>
  <script src="main.js" type="module"></script>
</body>

</html>

执行结果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐