一、NodeJs
Nodejs就像是一门服务端语言,面向服务端;可以直接开启服务;
const http = require('http');
http.createServer(function(request, resoponse) {
resoponse.writeHead(200, { 'Content-type': 'text/html' });
resoponse.end("<strong>我是莫松</strong>")
}).listen(8888)
console.log("运行成功");
输入完上面的代码以后,我们在浏览器输入localhost:8888就会出现我们的end里面的数据
使用node操作数据库:
//导入依赖
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
port: "3306",
user: "root",
password: "123456",
database: "saxon"
})
//连接
con.connect;
//数据查询
con.query("select id, name from account", function(error, results, fields) {
if (error) console.log("查询有错" + error);
console.log(JSON.stringify(results));
console.log(JSON.stringify(fields));
})
//关闭连接
con.end();
二、ES6
模板字符串:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var person = {
name: "saxon",
age: 18
}
//老版本
let sentence1 = "我是" + person.name + "今年" + person.age;
//新版本
let sentence = `我是${person.name},我今年${person.age}`
console.log(sentence);
</script>
</body>
</html>
函数默认值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function sum(a = 100, b = 200) {
return a + b;
}
//默认输出
console.log(sum());
//带上函数值传递,传递一个参数
console.log(sum(1000));
//传递两个参数
console.log(sum(200, 200));
</script>
</body>
</html>
如果你已经设置了默认值的话,在使用函数的时候不传递参数那么就使用默认值,如果传递一个就代替一个,以此类推
箭头函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function sum(a, b) {
return a + b;
}
console.log(`sum老式函数写法${sum(100,200)}`);
//变化成下面的格式
let sum2 = (a, b) => a + b + b;
console.log(`sum新式函数写法${sum2(200,200)}`);
</script>
</body>
</html>
//上面函数的输出结果
sum老式函数写法300
函数的箭头方法.html:18 sum新式函数写法600
对比的话,原来的格式是
function name(params) {
}
现在我们去掉一些东西,把我们的函数变成箭头函数
(params)=>{}
如果是只有一个参数,那么括号可以省略,如果只有返回参数,没有逻辑体,可以可以省略逻辑体括号
箭头函数的作用域this的指向
const a = {
aaa() {
console.log(this);
setTimeout(function () {
console.log(this);
}, 0);
setTimeout(()=>{console.log(this);})
},
}
a.aaa();
答案:
{aaa: ƒ}
Window {window: Window, self: Window, document: document, name: "", location: Location, …}
{aaa: ƒ}
如果使用箭头函数,会把我们的this向上找这个定义,不会直接使用windows对象,一直向外找,知道找到this为止
对象的简写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//原始写法
let name = "saxon";
let age = 18;
let person = {
name: name,
age: age,
go: function() {
console.log("早上我去学校上课");
}
}
console.log(JSON.stringify(person));
person.go();
//新式写法
//赋值采用key-value ,如果我们的key右边是变量,并且名字一样,那么可以直接简写
//如果属性是函数可以直接不用加function,直接写上 方法名+(){}就可以定义了
let person2 = {
name,
age,
go() {
console.log("对象简写,我去上课了");
}
}
console.log(JSON.stringify(person2));
person2.go()
</script>
</body>
</html>
我们知道这个以后,可以简写我们的ajax
//获得数据的过程
let text = $("#saxon").val;
let age = $("#age").val;
//老式写法
$.ajax({
url: "",
data: {
text: text,
age: age
},
success: function() {
}
})
//新式写法
//对象封装
let params = {
text,
age
}
$.ajax({
url: "",
data: params,
success() {}
})
对象的解构
//对象的属性的使用方法
//第一种 使用 类名+.
console.log(person.name);
//使用类名+["属性"]
console.log(person["name"]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let person = {
age: 18,
name: "saxon",
go() {
console.log("我是谁");
}
}
//老式写法
let age1 = person.age;
let name1 = person.name;
console.log(`名字是${name1},今年有${age1}岁了`);
//新式写法,变量名和对象的属性名要一致,函数也是一样
var {
age,
name,
go
} = person;
console.log(`名字是${name},今年有${age}岁了`);
go()
</script>
</body>
</html>
对象传播操作符
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let person = {
name: "saxon",
age: 18,
//属性是对象
user: {
name: "user",
age: 20
}
}
//如果我们想把某一些属性交给另一个对象的话,就可以用 对象传播操作符 ...来实现
//当前面已经取走一部分的数据的时候,我们再取的时候就只能取走剩下的部分
let { name, age, ...user } = person
console.log(name);
console.log(age);
console.log(user);
</script>
</body>
</html>
这个可以很好的把我们的属性从接收的json字符串里面解构出来,看起来更方便,类似于下面这个样的操作
我们可以把实际要用到的数据,使用一个对象来接受进行解构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//使用对象接收json字符串
let person = {
"name": "saxon",
"age": 18,
"pageSize": 10,
"currentPage": 20
}
let { pageSize, currentPage, ...user } = person
console.log(pageSize);
console.log(currentPage);
console.log(user);
</script>
</body>
</html>
map的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let persons = [{ name: "saxon", age: 18 }, { name: "sax", age: 20 }, { name: "on", age: 25 }]
//给每一个用户的年龄加1.可以使用map遍历数据
//map函数会把返回的数据填到自己的数组内,所以不可以简化成ele=>++(ele.age) 这个返回的会是一堆数字
let person = persons.map(ele => {
ele.age = ele.age + 1;
return ele
})
console.log(person);
</script>
</body>
</html>
reduce函数
文章:https://zhuanlan.zhihu.com/p/65235741
迭代运算
this.books.reduce((sum, b) => sum + b.count * b.price, 0)
Es6高阶函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<!-- filter函数:过滤器函数,一般用于数组,只要是使用了这个函数,如果是返回结果是true那么就把这个对应的元素加到一个新的数组里面 -->
<body>
<div id="app">
<button @click="getNumber">筛选</button>
<button @click="UpNumber">✖2</button>
<button @click="sum">求和</button>
<button @click="total">综合</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
book: [1, 200, 300, 55, 4, 5, 6, 9, 100]
},
methods: {
getNumber() {
//满足条件的放入到一个新的函数里面
let newarr = this.book.filter(n => n >= 100)
//100 200 300
console.log(newarr);
},
UpNumber() {
let newarr = this.book.map(n => n * 2)
console.log(newarr);
},
sum() {
let a = this.book.reduce((sum, a) => sum + a, 0)
console.log(a);
},
total() {
let a = this.book.filter(n => n >= 100).map(n => n * 2).reduce((sum, a) => sum + a, 0)
console.log(a);
}
}
}
)
</script>
</body>
</html>
babel
安装
npm install -g babel-cli
使用:
下载转码器:
npm install --save-dev babel-preset-latest
书写配置文件 .babelrc
这个点很重要
{
"presets": [],
"plugins": []
}
然后书写一段代码:
let a = 0
let go = () => {
console.log("GO");
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let newarr = arr.map(a => a * 2)
console.log(newarr);
go()
然后使用命令进行解析:
babel src -d dist
然后会发现在同级目录下会有一个dist文件,下面就有我们刚才写的文件转换过后的内容:
"use strict";
var a = 0;
var go = function go() {
console.log("GO");
};
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newarr = arr.map(function (a) {
return a * 2;
});
console.log(newarr);
go();
npm run 环境编写
"babel":"babel src -d dist""scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"babel":"babel src -d dist"
},
和前面有一样的效果,就是他会去配置文件里面的script里面寻找匹配的键值对命令
COMMONJS
模块化的导入和导出
导出:module.exports
function sum(a = 0, b = 0) {
return a + b;
}
function sub(a = 0, b = 0) {
return a - b;
}
module.exports={
sum, sub
}
导入:require()
const exp=require("./export")
console.log(exp.sum(100,200));
console.log(exp.sum());
console.log(exp.sub(100,200));
ES6
使用ES6实现模块化
导出:
export default {
getList() {
console.log("获得用户列表");
},
sum() {
console.log("数字相加");
}
}
导入:
import methods from "./导出"
methods.getList();
由于默认是不支持ES6的,所以我们要先使用babel来对ES6进行降级,具体的方法,前面已经写过了
降级过后的版本:
导出
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
getList: function getList() {
console.log("获得用户列表");
},
sum: function sum() {
console.log("数字相加");
}
};
导入:
"use strict";
var _ = require("./\u5BFC\u51FA");
var _2 = _interopRequireDefault(_);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_2.default.getList();
webpack
打包合并:
src/common.js
exports.info = (str) => {
console.log(str);
}
src/util.js
exports.add=(a,b)=>a+b;
主入口文件:src/main,js
const util=require("./util")
const info=require("./common")
info.info("hello world,"+util.add(100,200))
使用webpack打包 (webpack.config.js):
const path = require("path")
module.exports = {
//入口文件位置
entry: "./src/main.js",
//输出配置
output: {
//输出的位置
path:path.resolve(__dirname,"./dist"),
//输出的文件名字
filename:"bundle.js"
}
}
打包直接使用webpack就可以了;
打包以后的文件bundle.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
const util=__webpack_require__(1)
const info=__webpack_require__(2)
info.info("hello world,"+util.add(100,200))
/***/ }),
/* 1 */
/***/ (function(module, exports) {
exports.add=(a,b)=>a+b;
/***/ }),
/* 2 */
/***/ (function(module, exports) {
exports.info = (str) => {
console.log(str);
}
/***/ })
/******/ ]);
打包Css
下载Css-loader和style-loader
npm install --save-dev style-loader css-loader
创建文件style.css
body {
background-color: aqua;
}
新建规则:
const path = require("path")
module.exports = {
//入口文件位置
entry: "./src/main.js",
//输出配置
output: {
//输出的位置
path: path.resolve(__dirname, "./dist"),
//输出的文件名字
filename: "bundle.js"
},
module: {
rules: [
{
//使用多个loader的时候,从右往左识别,所以先写css,再写style
test: /\.css$/, //打包规则应用到以css结尾的文件上 test对应的不是字符串,不要加上冒号
use: ['style-loader', 'css-loader']
}
]
}
}
使用webpack命令合并文件
如果下载以后不可以使用可以先看看webpack的版本
打包文件
图片
npm install url-loader --save-dev
const path = require("path")
module.exports = {
//入口文件位置
entry: "./src/main.js",
//输出配置
output: {
//输出的位置
path: path.resolve(__dirname, "./dist"),
//输出的文件名字
filename: "bundle.js"
},
module: {
rules: [
{
//使用多个loader的时候,从右往左识别,所以先写css,再写style
test: /\.css$/, //打包规则应用到以css结尾的文件上 test对应的不是字符串,不要加上冒号
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name:"img/[name]-[hash:8].[ext]"
},
},
]
}
]
}
}
特别需要注意的是:
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name:"img/[name]-[hash:8].[ext]"
},
},
]
use里面是一个集合,但是loader的只可以是一个字符串,不应该是对象或者数组,name就是压缩以后的名字
结合babel
npm install --save-dev babel-loader@7 babel-core babel-preset-es2015
不知道为何,一直执行出错,所以我采用babel原生来降级
{
"presets": [
"es2015"
],
"plugins": []
}
{
"name": "y",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack && babel dist -d dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^5.0.1",
"file-loader": "^6.2.0",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1"
}
}
使用命令 npm run build
const path = require("path")
module.exports = {
//入口文件位置
entry: "./src/main.js",
//输出配置
output: {
//输出的位置
path: path.resolve(__dirname, "./dist"),
//输出的文件名字
filename: "bundle.js"
},
module: {
rules: [
{
//使用多个loader的时候,从右往左识别,所以先写css,再写style
test: /\.css$/, //打包规则应用到以css结尾的文件上 test对应的不是字符串,不要加上冒号
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: "img/[name]-[hash:8].[ext]"
},
},
]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use:
{
loader: "babel-loader",
options: {
presets: ["es2015"]
}
}
}
]
}
}