持续学习&持续更新中…
学习态度:守破离
// var 声明的变量往往会越域
// let 声明的变量有严格局部作用域
{
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceError: b is not defined
// var 可以声明多次
// let 只能声明一次
var m = 1
var m = 2
let n = 3
// let n = 4
console.log(m) // 2
console.log(n) // Identifier 'n' has already been declared
// var 会变量提升
// let 不存在变量提升
console.log(x); // undefined
var x = 10;
console.log(y); //ReferenceError: y is not defined
let y = 20;
// 1. 声明之后不允许改变
// 2. 一但声明必须初始化,否则会报错
const a = 1;
a = 3; //Uncaught TypeError: Assignment to constant variable.
//数组解构
let arr = [1,2,3];
// let a = arr[0];
// let b = arr[1];
// let c = arr[2];
let [a,b,c] = arr;
console.log(a,b,c)
const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}
// const name = person.name;
// const age = person.age;
// const language = person.language;
//对象解构
const { name, age, language } = person;
console.log(name, age, language)
// const { name: abc, age, language } = person;
// console.log(abc, age, language)
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 =
`
hello world
`;
console.log(ss);
// 2、字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
function fun() {
return "这是一个函数"
}
let info = `我是${name},今年${age + 10}了, 我想说: ${fun()}`;
console.log(info);
参数默认值:
//在ES6以前,我们无法给一个函数参数设置默认值,只能采用变通写法:
function add(a, b) {
// 判断b是否为空,为空就给默认值1
b = b || 1;
return a + b;
}
// 传一个参数
console.log(add(10));
//现在可以这么写:直接给参数写上默认值,没传就会自动使用默认值
function add2(a, b = 1) {
return a + b;
}
console.log(add2(20));
不定参数:
function fun(...values) {
console.log(values.length)
}
fun(1, 2) //2
fun(1, 2, 3, 4) //4
箭头函数:
//以前声明一个方法
// var print = function (obj) {
// console.log(obj);
// }
var print = obj => console.log(obj);
print("hello");
var sum = function (a, b) {
c = a + b;
return a + c;
}
var sum2 = (a, b) => a + b;
console.log(sum2(11, 12));
var sum3 = (a, b) => {
c = a + b;
return a + c;
}
console.log(sum3(10, 20))
const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}
function hello(person) {
console.log("hello," + person.name)
}
// var hello1 = (person) => console.log("hello," + person.name);
var hello1 = person => console.log("hello," + person.name);
hello1(person);
//箭头函数+解构
var hello2 = ({name}) => console.log("hello," +name);
hello2(person);
扩展方法:
const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}
console.log(Object.keys(person));//["name", "age", "language"]
console.log(Object.values(person));//["jack", 21, Array(3)]
console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]
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)
声明对象简写:
const age = 23
const name = "张三"
const person1 = { age: age, name: name }
const person2 = { age, name }
console.log(person2);
let person3 = {
name: "jack",
// 以前:
eat: function (food) {
console.log(this.name + "在吃" + food);
},
//箭头函数this不能使用,对象.属性
eat2: food => console.log(person3.name + "在吃" + food),
eat3(food) {
console.log(this.name + "在吃" + food);
}
}
person3.eat("香蕉");
person3.eat2("苹果")
person3.eat3("橘子");
对象拓展运算符:
// 1、拷贝对象(深拷贝)
let p1 = { name: "Amy", age: 15 }
let someone = { ...p1 }
console.log(someone) //{name: "Amy", age: 15}
let age1 = { age: 15 }
let name1 = { name: "Amy" }
let p2 = {name:"zhangsan"}
p2 = { ...age1, ...name1 }
console.log(p2)
//map():接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
let arr = ['1', '20', '-5', '3'];
// arr = arr.map((item)=>{
// return item*2
// });
arr = arr.map(item=> item*2);
//[2, 40, -10, 6]
console.log(arr);
//reduce() 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素
//arr.reduce(callback,[initialValue])
/**
1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
2、currentValue (数组中当前被处理的元素)
3、index (当前元素在数组中的索引)
4、array (调用 reduce 的数组)*/
let result = arr.reduce((a,b)=>{
console.log("上一次处理后:"+a);
console.log("当前正在处理:"+b);
return a + b;
} /*,100*/);
console.log(result)
原始写法:
//1、查出当前用户信息
//2、按照当前用户的id查出他的课程
//3、按照当前课程id查出分数
$.ajax({
url: "mock/user.json",
success(data) {
console.log("查询用户:", data);
$.ajax({
url: `mock/user_corse_${data.id}.json`,
success(data) {
console.log("查询到课程:", data);
$.ajax({
url: `mock/corse_score_${data.id}.json`,
success(data) {
console.log("查询到分数:", data);
},
error(error) {
console.log("出现异常了:" + error);
}
});
},
error(error) {
console.log("出现异常了:" + error);
}
});
},
error(error) {
console.log("出现异常了:" + error);
}
});
Promise可以封装异步操作,把死亡回调(回调嵌套)弄的符合人类的思考,一个任务下来接着一个任务执行:
let p = new Promise((resolve, reject) => {
$.ajax({
url: "mock/user.json",
success: function (data) {
console.log("查询用户成功:", data)
resolve(data);
},
error: function (err) {
reject(err);
}
});
});
p.then((obj) => {
return new Promise((resolve, reject) => {
$.ajax({
url: `mock/user_corse_${obj.id}.json`,
success: function (data) {
console.log("查询用户课程成功:", data)
resolve(data);
},
error: function (err) {
reject(err)
}
});
})
}).then((data) => {
console.log("上一步的结果", data)
$.ajax({
url: `mock/corse_score_${data.id}.json`,
success: function (data) {
console.log("查询课程得分成功:", data)
},
error: function (err) {
}
});
})
Promise的封装:
function get(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
data: data,
success: function (data) {
resolve(data);
},
error: function (err) {
reject(err)
}
})
});
}
get("mock/user.json")
.then((data) => {
console.log("用户查询成功~~~:", data)
return get(`mock/user_corse_${data.id}.json`);
})
.then((data) => {
console.log("课程查询成功~~~:", data)
return get(`mock/corse_score_${data.id}.json`);
})
.then((data) => {
console.log("课程成绩查询成功~~~:", data)
})
.catch((err) => {
console.log("出现异常", err)
});
function get(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
data: data,
success: resolve,
error: reject
})
});
}
get("mock/user.json")
.then(data => get(`mock/user_corse_${data.id}.json`))
.then(data => get(`mock/corse_score_${data.id}.json`))
.then(data => console.log("课程成绩查询成功~~~:", data))
.catch(err => console.log("出现异常", err))
hello.js:
// export const util = {
// sum(a, b) {
// return a + b;
// }
// }
// const util = {
// sum(a, b) {
// return a + b;
// }
// }
// export {util}
//`export`不仅可以导出对象,一切JS变量都可以导出。比如:基本类型变量、函数、数组、对象。
export default {
sum(a, b) {
return a + b;
}
}
user.js:
var name = "jack"
var age = 21
function add(a,b){
return a + b;
}
export {name,age,add}
main.js:
// import util from "./hello.js"
import abc from "./hello.js"
import {name,add} from "./user.js"
abc.sum(1,2);
console.log(name);
add(1,3);
Vue2教程:https://v2.cn.vuejs.org/v2/guide/
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<div id="app">
<h1> {{hello()}}h1>
<input type="text" v-model="num">
<button v-on:click="num++">点赞button>
<button v-on:click="cancle">取消点赞button>
<h1> {{name}} ,非常帅,有{{num}}个人为他点赞{{date}}h1>
div>
<script src="./node_modules/vue/dist/vue.js">script>
<script>
//1、vue声明式渲染
/*let vm = */
new Vue({
el: "#app",//绑定元素
data: { //封装数据
name: "张三",
num: 1,
date: new Date()
},
methods: { //封装方法
cancle() {
this.num--;
this.date = new Date();
},
hello() {
return "hello welcome"
}
}
});
//2、双向绑定:模型变化,视图变化。反之亦然。
//3、事件处理
//v-xx:指令
//1、创建vue实例,关联页面的模板,将自己的数据(data)渲染到关联的模板
//2、通过指令来简化对dom的一些操作。
//3、声明方法来做更复杂的操作。methods里面可以封装方法。
script>
body>
html>
v-text、v-html:
<div id="app">
{{msg}} {{1+1}} {{hello()}}<br/>
<span v-html="msg">span>
<br/>
<span v-text="msg">span>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
new Vue({
el:"#app",
data:{
msg:"Hello
",
link:"http://www.baidu.com"
},
methods:{
hello(){
return "World"
}
}
})
script>
v-bind:(单向绑定)
<div id="app">
<a v-bind:href="link">gogogoa>
<span v-bind:class="{active:isActive,'text-danger':hasError}"
:style="{color, fontSize: size}">你好span>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let vm = new Vue({
el: "#app",
data: {
link: "http://www.baidu.com",
isActive: true,
hasError: true,
color: '#fba',
size: '44px'
}
})
script>
v-model:(双向绑定)
<div id="app">
精通的语言:
<input type="checkbox" v-model="language" value="Java"> java<br/>
<input type="checkbox" v-model="language" value="PHP"> PHP<br/>
<input type="checkbox" v-model="language" value="Python"> Python<br/>
选中了 {{language}} <br>
{{language.join(",")}}
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let vm = new Vue({
el:"#app",
data:{
language: []
}
})
script>
v-on:(事件修饰符、按键修饰符)
<div id="app">
<button v-on:click="num++">点赞button>
<button @click="cancle">取消button>
<h1>有{{num}}个赞h1>
<div style="border: 1px solid red;padding: 20px;" v-on:click.once="hello">
大div
<div style="border: 1px solid blue;padding: 20px;" @click.stop="hello">
小div <br />
<a href="http://www.baidu.com" @click.prevent.stop>去百度a>
div>
div>
<input type="text" v-model="num"
v-on:keyup.up="num+=2"
@keyup.down="num-=2"
@click.ctrl="num=10"><br />
提示:
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
new Vue({
el:"#app",
data:{
num: 1
},
methods:{
cancle(){
this.num--;
},
hello(){
alert("点击了")
}
}
})
script>
v-for:
<div id="app">
<ul>
<li v-for="(user,index) in users" :key="user.name" v-if="user.gender == '女'">
当前索引:{{index}} ==> {{user.name}} ==> {{user.gender}} ==>{{user.age}} <br>
对象信息:
<span v-for="(v,k,i) in user">{{k}}=={{v}}=={{i}};span>
li>
ul>
<ul>
<li v-for="(num,index) in nums" :key="index">{{num}}li>
ul>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let app = new Vue({
el: "#app",
data: {
users: [{ name: '柳岩', gender: '女', age: 21 },
{ name: '张三', gender: '男', age: 18 },
{ name: '范冰冰', gender: '女', age: 24 },
{ name: '刘亦菲', gender: '女', age: 18 },
{ name: '古力娜扎', gender: '女', age: 25 }],
nums: [1,2,3,4,4]
},
})
script>
v-if、v-show:
<div id="app">
<button v-on:click="show = !show">点我呀button>
<h1 v-if="show">if=看到我....h1>
<h1 v-show="show">show=看到我h1>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let app = new Vue({
el: "#app",
data: {
show: true
}
})
script>
v-else、v-else-if:
<div id="app">
<button v-on:click="random=Math.random()">点我呀button>
<span>{{random}}span>
<h1 v-if="random>=0.75">
看到我啦?! >= 0.75
h1>
<h1 v-else-if="random>=0.5">
看到我啦?! >= 0.5
h1>
<h1 v-else-if="random>=0.2">
看到我啦?! >= 0.2
h1>
<h1 v-else>
看到我啦?! < 0.2
h1>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let app = new Vue({
el: "#app",
data: { random: 1 }
})
script>
<div id="app">
<ul>
<li>西游记; 价格:{{xyjPrice}},数量:<input type="number" v-model="xyjNum"> li>
<li>水浒传; 价格:{{shzPrice}},数量:<input type="number" v-model="shzNum"> li>
<li>总价:{{totalPrice}}li>
{{msg}}
ul>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
//watch可以让我们监控一个值的变化。从而做出相应的反应。
new Vue({
el: "#app",
data: {
xyjPrice: 99.98,
shzPrice: 98.00,
xyjNum: 1,
shzNum: 1,
msg: ""
},
computed: {
totalPrice() {
return this.xyjPrice * this.xyjNum + this.shzPrice * this.shzNum
}
},
watch: {
xyjNum(newVal, oldVal) {
if (newVal >= 3) {
this.msg = "库存不能超过3个";
this.xyjNum = 3
} else if (newVal <= 0) {
this.msg = "库存不能为负数";
this.xyjNum = 0
} else {
this.msg = ""
}
}
},
})
script>
<div id="app">
<ul>
<li v-for="user in userList">
{{user.id}} ==> {{user.name}} ==> {{user.gender}}
<br>
{{user.id}} ==> {{user.name}} ==> {{user.gender == 1?"男":"女"}}
<br>
{{user.gender | genderFilter}} ==> {{user.gender | gFilter}}
li>
ul>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
Vue.filter("gFilter", function (val) {
if (val == 1) {
return "男~~~";
} else {
return "女~~~";
}
})
let vm = new Vue({
el: "#app",
data: {
userList: [
{ id: 1, name: 'jacky', gender: 1 },
{ id: 2, name: 'peter', gender: 0 }
]
},
filters: {
filters 定义局部过滤器,只可以在当前vue实例中使用
genderFilter(val) {
if (val == 1) {
return "男";
} else {
return "女";
}
}
}
})
script>
<div id="app">
<button v-on:click="count++">我被点击了 {{count}} 次button>
<counter>counter>
<counter>counter>
<counter>counter>
<counter>counter>
<counter>counter>
<br>
<button-counter>button-counter>
<button-counter>button-counter>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
//1、全局声明注册一个组件
Vue.component("counter", {
template: ``,
data() {
return {
count: 1
}
}
});
//2、局部声明一个组件
const buttonCounter = {
template: ``,
data() {
return {
count: 1
}
}
};
new Vue({
el: "#app",
data: {
count: 1
},
components: {
'button-counter': buttonCounter
}
})
script>
xxx.vue:
<template>
<div>div>
template>
<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
export default {
//import引入的组件需要注入其中才能使用
components: {},
data() {
//这里存放数据
return {
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
},
//生命周期 - 创建完成(可以访问当前this实例)
created() {
},
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
},
beforeCreate() { }, //生命周期 - 创建之前
beforeMount() { }, //生命周期 - 挂载之前
beforeUpdate() { }, //生命周期 - 更新之前
updated() { }, //生命周期 - 更新之后
beforeDestroy() { }, //生命周期 - 销毁之前
destroyed() { }, //生命周期 - 销毁完成
activated() { }, //如果页面有keep-alive缓存功能,这个函数会触发
}
script>
<style scoped>
/* @import url(); 引入公共css类 */
style>
<div id="app">
<span id="num">{{num}}span>
<button @click="num++">赞!button>
<h2>{{name}},有{{num}}个人点赞h2>
div>
<script src="../node_modules/vue/dist/vue.js">script>
<script>
let app = new Vue({
el: "#app",
data: {
name: "张三",
num: 100
},
methods: {
show() {
return this.name;
},
add() {
this.num++;
}
},
beforeCreate() {
console.log("=========beforeCreate=============");
console.log("数据模型未加载:" + this.name, this.num);
console.log("方法未加载:" + this.show());
console.log("html模板未加载:" + document.getElementById("num"));
},
created: function () {
console.log("=========created=============");
console.log("数据模型已加载:" + this.name, this.num);
console.log("方法已加载:" + this.show());
console.log("html模板已加载:" + document.getElementById("num"));
console.log("html模板未渲染:" + document.getElementById("num").innerText);
},
beforeMount() {
console.log("=========beforeMount=============");
console.log("html模板未渲染:" + document.getElementById("num").innerText);
},
mounted() {
console.log("=========mounted=============");
console.log("html模板已渲染:" + document.getElementById("num").innerText);
},
beforeUpdate() {
console.log("=========beforeUpdate=============");
console.log("数据模型已更新:" + this.num);
console.log("html模板未更新:" + document.getElementById("num").innerText);
},
updated() {
console.log("=========updated=============");
console.log("数据模型已更新:" + this.num);
console.log("html模板已更新:" + document.getElementById("num").innerText);
}
});
script>
雷丰阳: Java项目《谷粒商城》Java架构师 | 微服务 | 大型电商项目).
本文完,感谢您的关注支持!