Vue 2.0 入门系列(15)学习 Vue.js 需要掌握的 es6 (2)

发布时间:2019-08-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue 2.0 入门系列(15)学习 Vue.js 需要掌握的 es6 (2)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

类与模块

es6 之前,通常使用构造函数来创建对象

// 构造函数 User
function User(username, email) {
    this.username = username;
    this.email = email;
}

// 为了让实例共享方法,将其添加到原型上
User.PRototyPE.changeEmail = function(newEmail) {
    this.email = newEmail;
}

// 使用
let user = new User("zen", "ihuangmx@qq.com")
user.changeEmail("change@qq.com");
console.LOG(user.email); //=> "change@qq.com"

es6 则可以写成

class User {
    // 实例化时,调用 constructor 方法,默认返回 this
    constructor(username, email) {
        this.username = username;
        this.email = email;
    }

    // 类的所有方法会自动绑定到原型对象上,包括 constructor
    changeEmail(newEmail) {
        this.email = newEmail;
    }
}

// 使用
let user = new User("zen", "ihuangmx@qq.com")
user.changeEmail("change@qq.com");
console.log(user.email); //=> "change@qq.com"

类中可以定义静态方法,也可以使用 getset 进行访问控制:

class User {
    constructor(username, email) {
        this.username = username;
        this.email = email;
    }

    changeEmail(newEmail) {
        this.email = newEmail;
    }

    static register(...args) {
        return new User(...args);
    }

    // 等价
    // static register(username, email) {
    //     return new User(username, email);
    // }

    get info() {
        return this.username + " " + this.email;
    }

    //  首字符大写
    set name(name) {
        this.username = name.slice(0,1).toUpperCase().concat(name.slice(1));
    }

    
}

// 使用
let user = User.register("zen", "ihuangmx@qq.com")
console.log(user.info)  // zen ihuangmx@qq.com
user.name = "jack" 
console.log(user.info)  // Jack ihuangmx@qq.com

类可以作为参数进行传递:

function log(strategy) {
    strategy.handle();
}

class ConsoleLogger {
    handle() {
        console.log("log log log");
    }
}

log(new ConsoleLogger);  //=> log log log

模块

TaskCollection.js 中定义一个类

class TaskCollection {
    constructor(tasks = []) {
        this.tasks = tasks;
    }

    dump() {
        console.log(this.tasks);
    }
}

main.js 中使用该类

const tc = new TaskCollection([
    'shop',
    'eat',
    'sleep'
]);

tc.dump();

index.htML - 显示页面。如果要使其生效的话,在不使用第三方库的情况下,只能将两个文件同时引入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <script src="TaskCollection.js">@H_564_360@</script>
    <script src="main.js"></script>
</body>
</html>

这样做的话,我们将无法看到彼此间的关联(main.js 加载 TaskCollection.js),因此,es6 提供了解方案,即模块。通过 exportimport 来实现

TaskCollection.js - 使用 export 命令显式指定输出的代码

// 输出类
export class TaskCollection {
    constructor(tasks = []) {
        this.tasks = tasks;
    }

    dump() {
        console.log(this.tasks);
    }
}

// 输出函数
export function foo(){
    console.log("foo");
}

// 输出变量
export let bar = 123;


// 可以统一输出,使其一目了然
// export {TaskCollection, foo, bar};

main.js - 使用 import 加载模块

import { TaskCollection, foo, bar as bar1 } From './TaskCollection';

const tc = new TaskCollection([
    'shop',
    'eat',
    'sleep'
]);

tc.dump();
foo();
console.log(bar1); 

index.html - 只需要引用 main.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <script src="main.js"></script>
</body>
</html>

由于当前的浏览器还不支持 es6 语法,我们可以使用打包工具。这里简单的举两个。

rollup.js

全局安装

$ cnpm install --global rollup

使用

$ rollup main.js --format iife --output bundle.js  # 针对客户端指定格式为 iife

然后只需要引用生成的 bundle.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <script src="bundle.js"></script>
</body>
</html>

webpack

安装

$ cnpm install -g webpack

打包

$ webpack main.js bundle.js

或者在当前项目下使用

$ cd webpack-demo-2
$ cnpm install webpack --save-dev

建立配置文件并设置

/webpack-demo-2/webpack.config.js

VAR webpack = require('webpack');

module.exports = {
    entry: './main.js',
    output: {
        filename: './dist/main.js'
    }
}

打包

$ webpack

通常是将其加入到 package.json

webpack-demo-2/package.json
{
  "devDependencies": {
    "webpack": "^2.5.1"
  },
  "scripts": {
      "build": "webpack"
  }
}

现在,只需要运行

$ cnpm run build

转换 js

可以注意到,rollupwebpack 都仅仅是将其打包,并没有转化为兼容的 js

// 部分打包后的代码
// dist/main.js
"use strict";
/* harmony export (immutable) */ __webpack_exports__["b"] = foo;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bar; });
// export 命令显式指定输出的代码
// 输出类
class TaskCollection {
    constructor(tasks = []) {
        this.tasks = tasks;
    }

    dump() {
        console.log(this.tasks);
    }
}

这里以 webpack 为例讲解如何转化为兼容的 js,首先安装相关工具

$ cnpm install --save-dev buble-loader buble

添加

/webpack-demo-2/webpack.config.js

var webpack = require('webpack');

module.exports = {
    entry: './main.js',
    output: {
        filename: './dist/main.js'
    },
    module: {
      loaders: [
        {
          test: /.js$/,
          loaders: 'buble-loader'
        }
      ]
    }
}

执行

$ cnpm run build

现在,可以发现已经转化为兼容的 js 了

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TaskCollection; });
/* harmony export (immutable) */ __webpack_exports__["b"] = foo;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bar; });
// export 命令显式指定输出的代码
// 输出类
var TaskCollection = function TaskCollection(tasks) {
    if ( tasks === void 0 ) tasks = [];

    this.tasks = tasks;
};

TaskCollection.prototype.dump = function dump () {
    console.log(this.tasks);
};

脚本宝典总结

以上是脚本宝典为你收集整理的Vue 2.0 入门系列(15)学习 Vue.js 需要掌握的 es6 (2)全部内容,希望文章能够帮你解决Vue 2.0 入门系列(15)学习 Vue.js 需要掌握的 es6 (2)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。