1. es6
The 6th edition of ECMA, released in 2015, stipulates new grammatical features
2. let
Declare variables
was | let |
---|---|
Declared variables will be jailbroken | Declared variables have strict scope |
Can be declared multiple times | Can only be declared once |
Variable promotion == (undeclared variables will not report an error) == | No variable promotion |
Code example:
<script>
// {
// var a = 1;
// let b = 2;
// }
// console.log(a);
// // Uncaught ReferenceError: b is not defined
// console.log(b);
// var a =1;
// var a =2;
// let b =11;
// let b = 22;
// // Identifier 'b' has already been declared
// console.log(a,b);
// undefined
console.log(aa);
var aa = 111;
// Cannot access 'bb' before initialization
console.log(bb);
let bb = 222;
</script>
3. const
Declare constants
- No modification is allowed after declaration
- Must be initialized once declared
const aaa = 111;
// Assignment to constant variable.
aaa = 222;
4. Destructuring expressions
<script>
let arr = [1, 2, 3];
/**数组**/
// let a = arr[0];
// let b = arr[1];
// let c = arr[2];
// console.log(a, b, c);
// let [a,b,c] = arr;
// console.log(a,b,c);
/**对象**/
const person = {
name: 'shigen',
age: 20,
hobby: ["1", "2", "3"]
}
// abc赋值为name
const {
name: abc, age, hobby} = person;
console.log(abc, age, hobby);
</script>
5. String
<script>
// 字符串拓展
let str = "hello.vue";
console.log(str.startsWith("hello")); // true
console.log(str.endsWith(".vue")); // true
console.log(str.includes("e")); // true
console.log(str.includes("hello")); // true
// 字符串模板
let ss = `<p>this is a <span>span</span></p>`;
console.log(ss);
// 字符串中插入变量和表达式
const person = {
name: "shigen",
age: 20
}
const {
name, age} = person;
function func() {
return "hello shigen";
}
// ${}中表达式
let info = `我是:${
name},我的年龄是 ${
age + 10 }, ${
func()}`;
console.log(info);
</script>
6. Function optimization
6.1 Default parameters of functions
function add(a, b) {
// b为空,b的值为1
b = b || 1;
return a + b;
}
6.2 Declaring methods with default values
function add2(a, b = 1) {
return a + b;
}
// 11 20
console.log(add2(10), add2(10, 10));
6.3 Indefinite parameters
function func(...values) {
console.log(`参数的长度${
values.length}`);
}
func(1,2);
// 参数的长度3
func(10,20,30);
6.4 Arrow functions
var print = function (obj) {
console.log(obj);
}
var print1 = obj => console.log(obj);
print1('hello');
var sum = function (a, b) {
return a + b;
}
var sum1 = (a, b) => a + b;
console.log(sum1(10, 20));
6.4.1 Arrow function + destructuring
const person = {
name : "zhangsan",
ls: [12,"12","122"]
}
function hello(person) {
console.log(`hello ${
person.ls}`);
}
// 箭头函数+解构
var hello1 = ({
ls}) => console.log(`hello ${
ls}`);
hello1(person);
7. Object optimization
7.1 Obtain keys
, values
,entries
const person = {
name : "zhangsan",
age: 21,
ls: [12,"12","122"]
}
console.log(Object.keys(person));
console.log(Object.values(person));
console.log(Object.entries(person));
7.2 assign
Aggregation
const target = {
a: 1};
const source1 = {
b: 2};
const source2 = {
c: 3};
// 要变成 {a:1,b:2,c:3}
Object.assign(target, source1, source2);
console.log(target);
7.3 Declaration object abbreviation
const age = 11;
const name ="shigen";
const person1 = {
age:age, name:name};
const person2 = {
age, name};
console.log(person2);
7.4 Abbreviation of function attributes of objects
let person3 = {
name: "shigen",
eat: function (food) {
console.log(`${
this.name} 在吃 ${
food}`);
},
// 获取不到this
eat2: food => console.log(`${
this.name} 在吃 ${
food}`),
eat3(food) {
console.log(`${
this.name} 在吃 ${
food}`);
}
}
person3.eat("apple");
person3.eat2("banana");
person3.eat3("orange");
7.5 Object expansion operator
7.5.1 Deep copy objects
// 对象的深拷贝
let p1 = {
name: "shigen", age:15};
let someone = {
...p1}
console.log(someone);
7.5.2 Merging objects
let age1 = {
age: 15}
let name1 = {
name: "zhangsan"}
let p2 = {
name: "lisi"}
p2 = {
...age1, ...name1}
// {age: 15, name: 'zhangsan'}
console.log(p2);
7.6 map
_reduce
7.6.1 map
Use
Accepts a function, processes all the elements in the original array with this function and puts them into the new array and returns
let arr = ['1', '-10', 45, '-100']
arr = arr.map(item => item*2);
// 2,-20,90,-200
console.log(arr.toString());
7.6.2 reduce
Use
Execute the callback function sequentially for each element in the array, excluding elements that are deleted or have never been assigned a value in the array
/**
* 1.previousValue 上一次调用回调的返回值/或者是提供的初始值:initialValue
* 2.currentValue 数组中当前被处理的元素
* 3.index
* 4. array 调用reduce的数组
*/
let result = arr.reduce((a,b) => {
console.log(`previousValue: ${
a} currentValue: ${
b}`);
return a+b;
}, 100);
// -128 ===> -28
console.log(`result: ${
result}`);
7.7 promise
andreject
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function get(url) {
/**
* resolve 成功往下传递
* reject 失败往下传递
*/
return new Promise((resolve, reject) => {
$.ajax({
url: url,
success: function (data) {
resolve(data);
},
error: function (data) {
reject(data);
}
})
})
}
get(`mock/user.json`)
.then((data) => {
console.log('查询用户成功', data);
return get(`mock/user_course_${
data.id}.json`);
})
.then((data) => {
console.log('课程查询成功', data);
return get(`mock/score_${
data.course_id}.json`);
})
.then((data) => {
console.log('成绩查询成功', data);
})
.catch((err) => {
console.log('出现异常', err);
});
</script>
8. Modularity
8.1 What is modularity
Split the code to facilitate reuse, similar to the import package in Java.
export
Used to specify the external interface of the module
import
Used to import functions provided by other modules
const util = {
sum(a, b) {
return a + b;
}
}
export {
util}
// ---------------------
import util from './util.js'
import {
name,age} from './user.js'
util.add(1,2);
9.Use of vue
9.1 Use of npm
npm init -y
npm install vue
9.2 Getting Started Demo
<div id="app">
<h2>{
{
name}} is good!</h2>
</div>
<script src="../../../js/vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
name: "shigen"
}
});
</script>
9.3 vue instructions
-
Interpolation expressions
{ {}}
can only be written in the tag body -
v-html
andv-text
-
v-bind:href='link'
Binding properties - one-way binding -
v-model
——- Two-way binding -
v-on
Binding events- event modifier
v-on:click=func()
or@click=func()
- Key modifier
v-on:keyup.up="num+=2"
- .stop: Prevent events from bubbling, equivalent to event.stopPropagation() in JavaScript
- .prevent: Prevent the execution of the preset behavior, equivalent to event.preventDefault() in JavaScript
- .capture: Capture bubbling
- .self: bind the event to itself, only itself can trigger it
- .once: trigger only once
- .passive: the default behavior of not blocking events
v-for
Traversev-if
andv-show
v-show
just control the display attribute value- Computed properties and listeners
<script>
let vm = new Vue({
el: '#app',
data: {
xyjPrice: 99.87,
shzPrice: 89.99,
xyjNum: 1,
shzNum: 1,
msg: ''
},
computed: {
totalPrice() {
return this.xyjNum * this.xyjPrice + this.shzNum* this.shzPrice;
}
},
watch: {
xyjNum(newVal, oldVal) {
if (newVal >= 3) {
this.msg = "不能超过三本";
this.xyjNum = 3;
} else {
this.msg = ''
}
}
}
});
</script>
- filter
Commonly used to handle text formatting operations, double bracket interpolation/v-bind expressions
<body>
<div id="app">
<ul>
<li v-for="(user,index) in userList">
{
{
user.name}} ==> {
{
user.gender === 1 ? '男' : '女'}} ==> {
{
user.gender | genderFilter }}
</li>
</ul>
</div>
<script src="../../../js/vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
userList: [
{
name: 'shigen', gender: 1},
{
name: 'zhangsan', gender: 0}
]
},
filters: {
genderFilter(gender) {
return gender === 1 ? '男' : '女';
}
}
})
</script>
</body>
// 定义全局的过滤器
Vue.filter('gFilter', function (val) {
return val === 1 ? '男' : '女';
})
10. Componentization of vue
10.1 Declare a component globally
The data of the component is the return of the method
<body>
<div id="app">
<button v-on:click="count++">被点击了 {
{
count}} 次</button>
<counter></counter>
</div>
<script src="../../../js/vue.js"></script>
<script>
Vue.component('counter', {
template: '<button v-on:click="count++">被点击了 {
{count}} 次</button>',
data() {
return {
count: 0
}
}
});
let vm = new Vue({
el: '#app',
data: {
count: 0
}
});
</script>
</body>
10.2 Declaring a component locally
const buttonCounter = {
template: '<button v-on:click="count++">被点击了 {
{count}} 次</button>',
data() {
return {
count: 0
}
}
};
components: {
'button-counter': buttonCounter
}
<button-counter></button-counter>
11. Life cycle
12.node.js
JavaScript running on the server
# 查看node的版本
node -v
# 运行node
node hello.js
hello js!