Guli College 160,000-word notes + 1,600 pictures (4) - front-end technology

Project source code and required information
Link: https://pan.baidu.com/s/1azwRyyFwXz5elhQL0BhkCA?pwd=8z59
Extraction code: 8z59

Article directory

demo04-front-end technology

1. Installation and use of VsCode

1.1 Download and install VsCode

1. In order to avoid bugs in the future, the version of VsCode I downloaded is the same as that of the teacher, which is version 1.29.1. Enter the download address in the url of Chrome: https://update.code.visualstudio.com/1.29.1/win32 -x64/stable and press Enter to download

2. If the download from the official website is very slow, you can copy the download link and use Thunder to download it, quack fast!

insert image description here

3. After the download is complete, you can directly install it in a fool-like way

1.2 Install plug-ins for VsCode

1. Click on the box circle

insert image description here

2. Search and install the following four plug-ins in the search bar (restart VsCode after installing these four plug-ins to make the plug-ins we installed take effect):

insert image description here

Chinese (Simplified) Language Pack for Visual Studio Code - Chinese Language Pack

Live Server - Open as an embedded server. In the past, if we want to access the static page 1.html, we need to put 1.html on the tomcat server, and then use the ip and port number to access 1.html. With this plug-in, we can directly open 1.html as an embedded server.

Vetur —— syntax highlighting, Intellisense, Emmet, etc. include formatting functions, Alt+Shift+F (format the full text), Ctrl+K Ctrl+F (format the selected code, two Ctrl need to be pressed at the same time)

vue-helper - add el before the code to load the complete elementUI code snippet

1.3 Create a workspace

1. Create an empty folder locally

insert image description here

2. Use vscode to open the empty folder created in the previous step

insert image description here

3. Save the folder as a workspace

① Click File –> Save Workspace As...

insert image description here

② Select the empty folder vs1010 created in step 1, and give the workspace a name (name it at will)

insert image description here

1.4 Create folders & files

① Right-click vs1010 and select "New Folder", here we create a folder named demo1

insert image description here

insert image description here

②Right click on demo1 and select "New File", here we create a file named demo1

insert image description here

insert image description here

③ Write code in 01.html

insert image description here

④Right click on the blank space and select "Open with Live Server", and then the default browser will be used to display 01.html (this is the credit for the Live Server plug-in we installed in "1.2 Installing Plug-ins for VsCode")

insert image description here

insert image description here

⑤By the way, let’s take a look at what it looks like if you open 01.html directly from the local:

insert image description here

2. es6 syntax

2.1let define variables

// var 声明的变量没有局部作用域
// let 声明的变量  有局部作用域
{
    
    
var a = 0
let b = 1
}
console.log(a)  // 0
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

2.2 const declares constants (read-only variables)

// 1、声明之后不允许改变    
const PI = "3.1415926"
PI = 3  // TypeError: Assignment to constant variable.
// 2、一但声明必须初始化,否则会报错
const MY_AGE  // SyntaxError: Missing initializer in const declaration

2.3 Destructuring assignment

Destructuring assignment is an extension to the assignment operator. It is a pattern matching for arrays or objects, and then assigns values ​​to the variables in it. In terms of code writing, it is concise and easy to read, and the semantics are clearer; it also facilitates the acquisition of data fields in complex objects.

//1、数组解构
// 传统
let a = 1, b = 2, c = 3
console.log(a, b, c)
// ES6
let [x, y, z] = [1, 2, 3]
console.log(x, y, z)
//2、对象解构
let user = {
    
    name: 'Helen', age: 18}
// 传统
let name1 = user.name
let age1 = user.age
console.log(name1, age1)
// ES6
let {
    
    name, age} =  user//注意:结构的变量必须是user中的属性
console.log(name, age)

2.4 Template Strings

The template string is equivalent to an enhanced version of the string. With the backtick `, in addition to being used as a normal string, it can also be used to define a multi-line string, and you can also add variables and expressions to the string.

// 1、多行字符串
let string1 =  `Hey,
can you stop angry now?`
console.log(string1)
// Hey,
// can you stop angry now?
// 2、字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
let name = "Mike"
let age = 27
let info = `My Name is ${
      
      name},I am ${
      
      age+1} years old next year.`
console.log(info)
// My Name is Mike,I am 28 years old next year.
// 3、字符串中调用函数
function f(){
    
    
    return "have fun!"
}
let string2 = `Game start,${
      
      f()}`
console.log(string2);  // Game start,have fun!

2.5 Declaration object shorthand

const age = 12
const name = "Amy"
// 传统
const person1 = {
    
    age: age, name: name}
console.log(person1)
// ES6
const person2 = {
    
    age, name}
console.log(person2) //{age: 12, name: "Amy"}

2.6 Define method shorthand

// 传统
const person1 = {
    
    
    sayHi:function(){
    
    
        console.log("Hi")
    }
}
person1.sayHi();//"Hi"
// ES6
const person2 = {
    
    
    sayHi(){
    
    
        console.log("Hi")
    }
}
person2.sayHi()  //"Hi"

2.7 Object extension operator

The spread operator (…) is used to extract all traversable properties of the parameter object and then copy them to the current object.

// 1、拷贝对象
let person1 = {
    
    name: "Amy", age: 15}
let someone = {
    
     ...person1 }
console.log(someone)  //{name: "Amy", age: 15}
// 2、合并对象
let age = {
    
    age: 15}
let name = {
    
    name: "Amy"}
let person2 = {
    
    ...age, ...name}
console.log(person2)  //{age: 15, name: "Amy"}

2.8 Arrow functions

Arrow functions provide a more concise way of writing functions. The basic syntax is:

parameter => function body

Arrow functions are mostly used to define anonymous functions

// 传统
var f1 = function(a){
    
    
    return a
}
console.log(f1(1))
// ES6
var f2 = a => a
console.log(f2(1))
// 当箭头函数没有参数或者有多个参数,要用 () 括起来。
// 当箭头函数函数体有多行语句,用 {} 包裹起来,表示代码块,
// 当只有一行语句,并且需要返回结果时,可以省略 {} , 结果会自动返回。
var f3 = (a,b) => {
    
    
    let result = a+b
    return result
}
console.log(f3(6,2))  // 8
// 前面代码相当于:
var f4 = (a,b) => a+b

3.vue

3.1 Vue entry case

1. Create the folder vuedemo under vs1010 in the workspace, and create the file 01-vue Getting Started.html under this folder. Then use the shortcut keys of vscode! Generate html code

insert image description here

insert image description here

2. Introduce js file in html

①The js file is in the data

insert image description here

② Paste the js file into the vuedemo folder created in step 1

insert image description here

③Introduce the js file in the 01-vue entry.html file

<script src="vue.min.js"></script>

insert image description here

3. Create a div tag on the html page and add an id attribute to the div tag

<!-- id标识vue作用的范围 -->
<div id="app">
</div>

insert image description here

4. Write vue code ( vue code is a fixed structure as follows )

<script>
    // 创建一个vue对象
    new Vue({
      
      
        el: '#app',//绑定vue作用的范围
        data: {
      
      //定义页面中显示的模型数据
            message: 'Hello Vue!'
        }
    })
</script>

insert image description here

el: '#app'The function is to get the label whose id is app, and write the content to the label. The bottom layer is actually the previously learned $("#app")

5. Use the interpolation expression to get the value defined in data

<!-- {
    
    {}} 插值表达式,绑定vue中的data数据 -->
{
   
   { message }}

insert image description here

6. The complete html code is as follows:

<!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>Document</title>
</head>
<body>
    <!-- id标识vue作用的范围 -->
    <div id="app">
        <!-- {
    
    {}} 插值表达式,绑定vue中的data数据 -->
        {
   
   { message }}
    </div>
    <script src="vue.min.js"></script>

    <script>
        // 创建一个vue对象
        new Vue({
      
      
            el: '#app',//绑定vue作用的范围
            data: {
      
      //定义页面中显示的模型数据
                message: 'Hello Vue!'
            }
        })
    </script>
</body>
</html>

insert image description here

7. Right click on the blank space and select "Open with Live Server" to see the effect on the page

insert image description here

insert image description here

3.2 Extract code snippets

1. Select "File –> Preferences –> User Code Snippets"

insert image description here

2. Click "New Global Snippet File..."

insert image description here

3. Give it a name at will, and after clicking "Save", vscode will automatically open this file

insert image description here

insert image description here

4. Delete all the code in the file

insert image description here

5. Copy and paste the following code into the file

{
	"vue htm": {
		"scope": "html",
		"prefix": "vuehtml",
		"body": [
			"<!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>Document</title>",
			"</head>",
			"",
			"<body>",
			"    <div id=\"app\">",
			"",
			"    </div>",
			"    <script src=\"vue.min.js\"></script>",
			"    <script>",
			"        new Vue({",
			"            el: '#app',",
			"            data: {",
			"                $1",
			"            }",
			"        })",
			"    </script>",
			"</body>",
			"",
			"</html>",
		],
		"description": "my vue template in html"
	}
}

insert image description here

6. Create the file "02-test code fragment.html" in the vuedemo folder, and type vue in the file, then vscode will give us a prompt, and we will automatically complete the code after clicking this prompt

insert image description here

insert image description here

3.3 Basic data rendering and instructions

The v-bind feature is called a directive. Instructions are prefixed with v-

In addition to using the interpolation expression { {}} for data rendering, you can also use the v-bind command, its shorthand form is a colon (:)

new Vue({
    
    
    el: '#app',
    data: {
    
    
        content: '我是标题',
        message: '页面加载于 ' + new Date().toLocaleString()
    }
})
<div id="app">
    <!-- 如果要将模型数据绑定在html属性中,则使用 v-bind 指令
         此时title中显示的是模型数据
    -->
    <h1 v-bind:title="message">
        {
   
   {content}}
    </h1>
    <!-- v-bind 指令的简写形式: 冒号(:) -->
    <h1 :title="message">
        {
   
   {content}}
    </h1>
</div>

3.4 One-way and two-way data binding

Two-way data binding with v-model

new Vue({
    
    
    el: '#app',
    data: {
    
    
        searchMap:{
    
    
            keyWord: '尚硅谷'
        }
    }
})
<div id="app">
	<!-- v-bind:value只能进行单向的数据渲染 -->
    <input type="text" v-bind:value="searchMap.keyWord">
    <!-- v-model 可以进行双向的数据绑定  -->
    <input type="text" v-model="searchMap.keyWord">
    <p>您要查询的是:{
   
   {searchMap.keyWord}}</p>
</div>
  • The one-way binding here is v-bind:value="..."the two-way binding v-model="...", and the two-way here does not need to be written compared to the one-way:value
  • One-way binding is: take the value from data, and the change of its own value will not cause the change of the value in the data
  • Two-way binding is: not only can you get the value from data, but the change of its own value will also cause the change of the value in the data

3.5 Binding events

new Vue({
    
    
    el: '#app',
    data: {
    
    
         //查询结果
         result: {
    
    }
    },
    methods:{
    
    
        search(){
    
    
            console.log('search')
            this.result = {
    
    
                "title":"尚硅谷",
                "site":"http://www.atguigu.com"
            }
        }
    }
})
<div id="app">
    <!-- v-on 指令绑定事件,click指定绑定的事件类型,事件发生时调用vue中methods节点中定义的方法 -->
    <button v-on:click="search()">查询1</button>
    <!-- vue绑定事件简写 -->
    <button @click="search()">查询2</button>
    <p><a v-bind:href="result.site" target="_blank">{
   
   {result.title}}</a></p>
</div>

The following is the initial appearance of the opened page:

insert image description here

Click Query 1 or Query 2 in the opened page:

insert image description here

3.6 Modifiers

Modifiers are special suffixes indicated by periods (.) that indicate that a command should be bound in a special way.

For example, the .prevent modifier tells the v-on directive to call event.preventDefault() on triggered events:

That is, to prevent the original default behavior of the event

new Vue({
    
    
    el: '#app',
    data: {
    
    
        user:{
    
    }
    },
    methods:{
    
    
        onSubmit() {
    
    
            if (this.user.username) {
    
    
                console.log('提交表单')
            } else {
    
    
                alert('请输入用户名')
            }
        }
    }
})
<div id="app">
    <!-- 修饰符用于指出一个指令应该以特殊方式绑定。
         这里的 .prevent 修饰符告诉 v-on 指令对于触发的事件调用js的 event.preventDefault():
         即阻止表单提交的默认行为 -->
    <form action="save" v-on:submit.prevent="onSubmit">
        <label for="username">
            <input type="text" id="username" v-model="user.username">
            <button type="submit">保存</button>
        </label>
    </form>
</div>

This example is: the "Save" button was originally clicked to submit, but because the modifier .prevent is used, it is no longer submitted here, but the onSubmit method written by ourselves is called

The following is the initial appearance of the opened page:

insert image description here

Write nothing in the input box and click "Save" and a prompt box will pop up:

insert image description here

Write something in the input box and click "Save" to print "Submit Form" on the console

insert image description here

3.7 Conditional Rendering

3.7.1v-if conditional instruction

new Vue({
    
    
    el: '#app',
    data: {
    
    
        ok: false
    }
})
<div id="app">
    <input type="checkbox" v-model="ok">是否同意
    <!-- v:if条件指令:还有v-else、v-else-if 切换开销大 -->
    <h1 v-if="ok">同意</h1>
    <h1 v-else>不同意</h1>
</div>

If yes ok: truethen this checkbox is checked by default. Here is ok: falsewhy this check box is not checked by default, and the initial appearance of opening the page is not checked:

insert image description here

After ticking the checkbox:

insert image description here

3.7.2 v-show conditional instruction

new Vue({
    
    
    el: '#app',
    data: {
    
    
        ok: false
    }
})
<div id="app">
    <input type="checkbox" v-model="ok">是否同意
    <h1 v-show="ok">同意</h1>
    <h1 v-show="!ok">不同意</h1>
</div>

3.7.3 The difference between v-if and v-show

  • v-ifis "true" conditional rendering, as it will ensure that event listeners and child components inside the conditional block are properly destroyed and recreated during the transition.
  • v-ifAlso lazy : if the condition is false on initial render, do nothing - the conditional block won't start rendering until the condition becomes true for the first time.
  • In contrast, v-showit's much simpler - the element is always rendered no matter what the initial condition is, and is simply toggled based on CSS.
  • In general, v-ifhas a higher switching overhead, while v-showhas a higher initial rendering overhead. Therefore, it is better to use if you need to switch very frequently, or better v-showto use if conditions rarely change during runtime v-if.

3.8 List Rendering

Example 1: Simple List Rendering

new Vue({
    
    
    el: '#app'
})
<div id="app">
    <ul>
        <li v-for="n in 5"> {
   
   { n }} </li>
    </ul>

    <ol>
        <!-- 如果想获取索引,则使用index关键字,注意,圆括号中的index必须放在后面 -->
        <li v-for="(n, index) in 5">{
   
   { n }} -- {
   
   { index }}</li>
    </ol>
</div>

insert image description here

Example 2: Traversing the data list

new Vue({
    
    
    el: '#app',
    data: {
    
    
        userList: [
            {
    
     id: 1, username: 'helen', age: 18 },
            {
    
     id: 2, username: 'peter', age: 28 },
            {
    
     id: 3, username: 'andy', age: 38 }
        ]
    }
})
<div id="app">
    <table border="1">
        <!-- <tr v-for="item in userList"></tr> -->
        <tr v-for="(item, index) in userList">
            <td>{
   
   {index}}</td>
            <td>{
   
   {item.id}}</td>
            <td>{
   
   {item.username}}</td>
            <td>{
   
   {item.age}}</td>
        </tr>
    </table>
</div>

insert image description here

3.9 components

3.9.1 Local Components

Define components:

new Vue({
    
    
    el: '#app',
    // 定义局部组件,这里可以定义多个局部组件
    components: {
    
    
        //组件的名字(随便起名)
        'mxy': {
    
    
            //组件的内容
            template: '<ul><li>首页</li><li>学员管理</li></ul>'
        }
    }
})

Use components:

<div id="app">
    <mxy></mxy>
</div>

insert image description here

3.9.2 Global components

The partial components created above can only be used on the current page. We can make the components we create available to any page by creating a global component

1. Create the folder components under the vuedemo folder, and create the file mxy.js under the folder, and then write the code in the file

// 定义全局组件
Vue.component('mxymxy', {
    
    
    template: '<ul><li>首页</li><li>学员管理</li><li>讲师管理</li></ul>'
})

insert image description here

2. Create an html page, use the method in "3.2 Extract code snippets" to quickly generate html code, and add two lines of code in the body tag

insert image description here

3. Go to the page to view the effect

insert image description here

3.10 Instance life cycle

The lifecycle of an instance is as follows:

insert image description here

We only need to focus on the created method (executed before page rendering) and mounted method (executed after page rendering)

3.11 Routing

1. Create the file "12-vue routing.html" under the vuedemo folder, and then use the method in "3.2 Extracting code snippets" in this file to quickly generate HTML code

insert image description here

2. Routing needs to introduce the vue-router library

① There is a js file of vue-router in the data

insert image description here

② Paste the js file into the vuedemo folder

insert image description here

③Introduce the js file of vue-router

<script src="vue-router.min.js"></script>

insert image description here

Note: Be sure to introduce vue.min.js first, and then import vue-router.min.js

3. Write html

<div id="app">
    <h1>Hello App!</h1>
    <p>
        <!-- 使用 router-link 组件来导航. -->
        <!-- 通过传入 `to` 属性指定链接. -->
        <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
        <router-link to="/">首页</router-link>
        <router-link to="/student">会员管理</router-link>
        <router-link to="/teacher">讲师管理</router-link>
    </p>
    <!-- 路由出口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>

insert image description here

  • to="/", to="/student", to="/teacher"is the jump path
  • When we click "Home Page" or "Member Management" or "Lecturer Management", the content must be displayed, right? Where should the content be displayed? Displayed in the router-view tag

4. Write js (replace the third script tag in the page with the following code)

<script>
    // 1. 定义(路由)组件。
    // 可以从其他文件 import 进来
    const Welcome = {
    
     template: '<div>欢迎</div>' }
    const Student = {
    
     template: '<div>student list</div>' }
    const Teacher = {
    
     template: '<div>teacher list</div>' }
    
    // 2. 定义路由
    // 每个路由应该映射一个组件。
    const routes = [
        {
    
     path: '/', redirect: '/welcome' }, //设置默认指向的路径
        {
    
     path: '/welcome', component: Welcome },
        {
    
     path: '/student', component: Student },
        {
    
     path: '/teacher', component: Teacher }
    ]
    
    // 3. 创建 router 实例,然后传 `routes` 配置
    const router = new VueRouter({
    
    
        routes // (缩写)相当于 routes: routes
    })
    
    // 4. 创建和挂载根实例。
    // 从而让整个应用都有路由功能
    const app = new Vue({
    
    
        el: '#app',
        router
    })
</script>

insert image description here

5. After the code is written, go to the page to view the effect by yourself

4.axios

Axios is an independent project, not a part of vue. Axios is often used together with vue to implement ajax operations

1. Create a folder axiosdemo in the workspace, create a file 01.html in this folder, and then use the method in "3.2 Extracting Code Snippets" in this file to quickly generate HTML code

insert image description here

2. There are js files of vue and axios in the data

insert image description here

insert image description here

3. Paste these two js files into the axiosdemo folder created in step 1

insert image description here

4. The js file of vue has been introduced in the html code generated by the shortcut, so we only need to introduce the js file of axios in html

<script src="axios.min.js"></script>

insert image description here

5. There is a fixed structure when using axios to send an ajax request, we write the following fixed structure in 01.html:

//固定的结构
new Vue({
    
    
    el: '#app',
    data: {
    
     //在data定义变量和初始值
    },
    created() {
    
     //该方法在页面渲染之前执行,我们一般在该方法中调用定义的方法
    },
    methods:{
    
     //编写具体的方法
    }
})

insert image description here

6. In practical applications, we must use ajax requests to call the back-end interface to obtain data. There is a lot of knowledge that has not been explained when adjusting the interface, so here we do not adjust the interface, but make a set of simulated data in the file, and then request the file to get the data.

So here we first create a file data.json in the axiosdemo folder and write the simulation data in the file:

{
    
    
    "success":true,
    "code":20000,
    "message":"成功",
    "data":{
    
    
        "items":[
            {
    
    "name":"lucy","age":20},
            {
    
    "name":"mary","age":30},
            {
    
    "name":"jack","age":40}
        ]
    }
}

insert image description here

7. Use axios to send an ajax request, request the file data.json created in step 6, get the data, and display the obtained data on the page

①Change 01.html to new Vue({...})the following code

//固定的结构
new Vue({
    
    
    el: '#app',
    data: {
    
     //在data定义变量和初始值
        //定义变量:值空的数组
        userList:[]
    },
    created() {
    
     //该方法在页面渲染之前执行,我们一般在该方法中调用定义的方法
        //调用定义的方法(this表示当前vue对象)
        this.getUserList()
    },
    methods:{
    
     //编写具体的方法
        //创建方法用来查询所有用户数据
        getUserList() {
    
    
            //使用axios发送ajax请求
            //格式:axios.提交方式("请求的接口/文件的路径")
            axios.get("data.json")
                .then(response => {
    
     //请求成功就执行then方法
                //response就是请求成功之后返回的信息
                console.log(response)
            })
                .catch(error => {
    
     //请求失败就执行catch方法
                
            })
        }
    }
})

insert image description here

  • Because the data we want to get is the items in data.json, and this data is an array, so write this line of code in data:userList:[]
  • The information returned after the successful request interface/file is assigned to the response in .then(response => …). Note: It is not necessary to write response, it can be written casually
  • The error message returned after the request interface/file fails is assigned to error in .then(error => …). In the same way, it is not necessary to write error, it can be written casually

②Look at the print of the console on the page

insert image description here

The response in .then is the information returned after the request is successful, which is the part circled by the big box in the above picture, but we only want the items in this information, so we need to use it. The last data obtained by this line of code is what we response.data.data.items want array data to be

③ Then we can add the following code to .then(…) so that we can get the data we want and assign the data to userList

//将数组数据赋值给userList
this.userList = response.data.data.items

insert image description here

④ Next, we need to display the data in the userList array. Write the following code in the div tag:

<!-- 把userList数组里面的数据显示 -->
<div v-for = "user in userList">
    {
   
   {user.name}} -- {
   
   {user.age}}
</div>

insert image description here

⑤ Go to the page to view

insert image description here

⑥Complete code of body tag:

<body>
    <div id="app">
        <!-- 把userList数组里面的数据显示 -->
        <div v-for = "user in userList">
            {
   
   {user.name}} -- {
   
   {user.age}}
        </div>
    </div>
    <script src="vue.min.js"></script>
    <script src="axios.min.js"></script>
    <script>
        //固定的结构
        new Vue({
      
      
            el: '#app',
            data: {
      
       //在data定义变量和初始值
                //定义变量:值空的数组
                userList:[]
            },
            created() {
      
       //该方法在页面渲染之前执行,我们一般在该方法中调用定义的方法
                //调用定义的方法(this表示当前vue对象)
                this.getUserList()
            },
            methods:{
      
       //编写具体的方法
                //创建方法用来查询所有用户数据
                getUserList() {
      
      
                    //使用axios发送ajax请求
                    //格式:axios.提交方式("请求的接口/文件的路径")
                    axios.get("data.json")
                        .then(response => {
      
       //请求成功就执行then方法
                            //response就是请求成功之后返回的信息
                            console.log(response)

                            //将数组数据赋值给userList
                            this.userList = response.data.data.items
                        })
                        .catch(error => {
      
       //请求失败就执行catch方法

                        })
                }
            }
        })
    </script>
</body>

insert image description here

5.element-ui

Official website: https://element.eleme.cn/#/zh-CN

6.node.js

6.1 Introduction to node.js

1. What is node.js:

Simply put, node.js is JavaScript running on the server side

2. What is the use of node.js:

① When we learn java, we need a jdk environment to run the program. The role of node.js to JavaScript is equivalent to that of jdk to java: node.js is the operating environment of JavaScript and is used to execute JavaScript code . We introduced the js file into the html page (such as: <script src="vue.min.js"></script>), and then accessed the html page through the browser to make the js file execute. With node.js, you don’t need a browser, just use node.js directly Can run JavaScript code

② Simulate server effect, such as tomcat

6.2 Download and install node.js

1. Enter https://nodejs.org/en/ in the Chrome address bar to enter the official website, and then click "Other Downloads"

insert image description here

2. Click "All download options"

insert image description here

3. Click "…/" to enter the upper level directory

insert image description here

4. Find the version 10.14.2 that is the same as in the video and click to enter

insert image description here

5. My computer is 64-bit, so click "node-v10.16.3-x64.msi" to download (I copied the download link and downloaded it with Thunder)

insert image description here

6. After the download is complete, perform a fool-like installation (Note: It is best to install to the c drive by default, do not modify its installation address)

insert image description here

7. Check whether the installation is successful:

Open the command line window and enter the node -v command. If you can see the version number, the installation is successful.

insert image description here

6.3 Using node.js to execute JavaScript code

1. Create the file 01.js under the axiosdemo folder and write the code

console.log('hello nodejs')

insert image description here

2. Find the folder where the 01.js created in the previous step is located, enter cmd in the address bar and press Enter

insert image description here

3. Enter node 01.js in the opened command line window

insert image description here

6.4 Simulation server (understand)

1. Create the file 02.js under the axiosdemo folder and write the code

const http = require('http');
http.createServer(function (request, response) {
    
    
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {
    
    'Content-Type': 'text/plain'});
    // 发送响应数据 "Hello World"
    response.end('Hello Server');
}).listen(8888);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

insert image description here

2. Find the folder where the 02.js created in the previous step is located, enter cmd in the address bar and press Enter to enter the command line window under the path, enter node 02.js in the command line window to run the server program

insert image description here

3. Enter in the address bar http://localhost:8888/to see the output html page

insert image description here

4. Press ctrl+c in the command line window to stop the service

insert image description here

6.5 Open the cmd window in vscode and execute the js code

Our js code is written in vscode, but the execution of js code is executed in the command line window, which is very inconvenient. The solution is: open the command line window directly in vscode

1. Right-click axiosdemo and select "Open in Terminal"

insert image description here

2. A pop-up box will pop up at this point, we click "Customize"

insert image description here

3. Both cmd and powershell are available, I use cmd here

insert image description here

4. Input node 01.js in the cmd window may prompt 'node'不是内部或外部指令,也不是可运行的程序或批处理文件。, if prompted, restart vscode and try, if the problem is not resolved, then run vscode as an administrator (the problem is solved after I restart vscode)

insert image description here

5. After restarting vscode, the js code of 01.js can be executed normally

insert image description here

7. npm package management tool

7.1 Introduction to npm

1. What is npm:

The full name of NPM is Node Package Manager. It is a Node.js package management tool and the world's largest module ecosystem. All modules in it are open source and free. It is also tool, which manages front-end js dependencies and downloads js online rely. Equivalent to Maven on the backend.

7.2 Install npm

When installing node.js, npm will also be installed automatically. The location of npm packages and tools installed by default in node.js: node.js directory\node_modules

insert image description here

Use the command npm -v in any command line window to check whether npm is installed successfully

insert image description here

7.3 npm initialize project

1. Create an npmdemo folder in the workspace, then right-click the folder and select "Open in Terminal"

insert image description here

2. Use the command npm init to initialize the folder as a front-end project

insert image description here

3. It’s stuck here right now, it’s waiting for us to set the package name, if we press Enter without entering anything, then the package name is the default in the bracketsnpmdemo

#按照提示输入相关信息,如果是用默认值则直接回车即可。
#package name: 项目包名/名称
#version: 项目版本号
#description: 项目描述
#entry point: 程序入口(后端入口一般是main方法,前端入口一般是js文件)
#keywords: {Array}关键词,便于用户搜索到我们的项目

We all use the default here, you don’t need to enter anything, just press Enter all the way

insert image description here

4. Enter all the way until we confirm the information and enteryes

insert image description here

5. At this point, the initialization of the front-end project is completed. You can see that there is a package.json file under the npmdemo folder. This is the configuration file of the package, which is equivalent to maven's pom.xml. We can also modify package.json as needed. Revise

insert image description here

6. If the package name, version, description, etc. of a front-end project initialized in the future use the default ones, the above three steps 2, 3, and 4 are too cumbersome, and you can directly replace these three steps with one command: npm init -y

7.4 npm download js dependencies

7.4.1 Configure npm to use Taobao image

If you do not configure npm to use the Taobao mirror, you will download js dependencies from the external network, which will be very slow or even fail to download.

Execute the following command in the command line window of vscode:

npm config set registry https://registry.npm.taobao.org

insert image description here

Use the following command to view the npm configuration information and see if we have successfully configured the Taobao image:

npm config list

insert image description here

7.4.2 Command npm install dependency name@version number

The command to download dependencies is that npm install 依赖名称@版本号if you don’t write it @版本号, you will download the latest version. In order to avoid pitfalls in the future, we use the following command to download the jquery dependencies that are the same as the teacher’s version (version 3.4.1). And we will find that there are two more things after downloading jquery dependencies: folder node_modules and file package-lock.json

npm install [email protected]

insert image description here

  • The downloaded dependencies are in the node_modules folder

  • The function of the package-lock.json file: lock the currently downloaded dependent version, only this version can be downloaded, and other versions cannot be downloaded

7.4.3 Command npm install

If there is no dependent node_modules folder in the project sent to me (in most cases, there is no node_modules folder, because this folder is usually very large, there are many small files, and some dependencies cannot be cross-platform), only package.json and package-lock.json, then we can download the specified version of dependencies recorded in package-lock.json through the following command

npm install

insert image description here

insert image description here

7.4.4 Difference between package.json and package-lock.json

Difference one:

  • The version numbers of dependencies in package.json have a ^, which means backward (new) compatible dependencies, because the latest version of jquery exceeds 3.4.1 and the major version of the latest version and the major version of 3.4.1 (what is the major version : The major version of 3.4.1 is the same as 3), so when using the npm install command to download jquery dependencies, the latest version of jquery dependencies will be downloaded instead of the 3.4.1 version recorded in package.json
  • However, executing npm install will definitely download the specified version of dependencies recorded in package-lock.json, and there is no backward (new) compatible dependency.

Take our project as an example and prove:

There are jquery dependencies recorded in package.json: "jquery": "^3.4.1"we do this: ①Delete the node_modules folder and package-lock.json in the project

insert image description here

② Execute the npm install command on the terminal to download dependencies, and after execution, the node_modules folder and package-lock.json will be generated for us

insert image description here

③ Found that the jquery dependency we just downloaded is the latest version 3.6.0 instead of the 3.4.1 version recorded in package.json

insert image description here

insert image description here

④I just copied the code in the package-lock.json file generated after executing the npm install [email protected] command in "7.4.2 command npm install dependency name@version number", as follows:

{
  "name": "npmdemo",
  "version": "1.0.0",
  "lockfileVersion": 1,
  "requires": true,
  "dependencies": {
    "jquery": {
      "version": "3.4.1",
      "resolved": "https://registry.npmmirror.com/jquery/-/jquery-3.4.1.tgz",
      "integrity": "sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw=="
    }
  }
}

⑤We first delete all the codes in the package-lock.json file generated in step ③, and then copy and paste the code listed in step ④ into the package-lock.json file

insert image description here

⑥Delete the node_modules folder

insert image description here

⑦ Execute the npm install command on the terminal to download dependencies

⑧ After executing the command, the node_modules folder will be generated. Let’s check the jquery version downloaded now and find that the downloaded version is the version 3.4.1 specified in package-lock.json instead of downloading the latest version

insert image description here

Difference two:

For example, if my project downloads version A dependency of version 1.2, and A dependency depends on version B dependency of version 2.2, then only A dependency and version will be recorded in package.json (but the latest version may be downloaded when downloading dependency, explain in detail See "Difference 1" above), but B dependency is not recorded; but package-lock.json not only records A dependency and version, but also records B dependency and version

7.5 Other commands (temporarily familiar)

#当前工作区安装包、工具
npm install --save-dev webpack
#下面这个是npm install --save-dev webpack的简写
npm install -D webpack

#全局安装包、工具
npm install -global webpack
#下面这个是npm install -global webpack的简写
npm install -g webpack

#更新包(更新到最新版本)
npm update 包名

#全局更新
npm update -g 包名

#卸载包
npm uninstall 包名

#全局卸载
npm uninstall -g 包名
  • Packages and tools installed in the current workspace can only be used in the current workspace, and cannot be used in other workspaces
  • Globally installed packages and tools: as long as they are in the node.js environment, all workspaces can be used
  • The location of globally installed packages and tools: user directory\AppData\Roaming\npm\node_modules

8. Babel transcoder

8.1 Introduction

Babel is a widely used transcoder that can convert ES6 code to ES5 code

Why do we need to convert ES6 code to ES5 code? Because the code we write now is es6 code, but the browser compatibility of es6 code is very poor, and there are many es6 codes that low-level browsers do not know

8.2 Project initialization

1. Create a babeldemo folder under the workspace

insert image description here

2. Use the command npm init -y to initialize the project in the terminal

insert image description here

8.3 Install the command line transcoding tool

Babel provides the babel-cli tool for transcoding on the command line. Use the following command to install the babel-cli tool in the terminal (in order to be the same as the teacher's version, I added it @6.26.0)

npm install --global [email protected]

insert image description here

After the installation is complete, use the following command to check whether the installation is successful

babel --version

insert image description here

8.4 Writing es6 code

1. Create a folder es6 under the babeldemo folder, and create a file 01.js under this folder, and then write the code of es6 in this file

// 转码前
// 定义数据
let input = [1, 2, 3]
// 将数组的每个元素 +1
input = input.map(item => item + 1)
console.log(input)

insert image description here

How to see if it is es6 code?

There is a best way to distinguish: as long as there is an arrow function (parameter => function body), it must be es6 code, because there is no arrow function es5

8.5 Configuration.babelrc

Create a configuration file .babelrc (only this name!!) in the root directory of the project (that is, under the babeldemo folder). This file is used to set transcoding rules and plug-ins . The basic format is as follows:

{
    
    
    "presets": [],
    "plugins": []
}

Among them, the presets field is used to set the transcoding rules, we will add the es2015 rules to .babelrc

{
    
    
    "presets": ["es2015"],
    "plugins": []
}

insert image description here

8.6 Install Transcoder

Use the following command to install the es2015 transcoder in the project ( @6.24.1是为了安装和老师一样的版本)

npm install --save-dev [email protected]

insert image description here

8.7 Transcoding

There are two ways to use command transcoding:

  • transcode by file
  • Transcode by folder

8.7.1 Transcoding according to the file

1. First create two folders under the babeldemo folder: dist1 and dist2

insert image description here

2. Use the following command to complete "transcoding according to the file"

babel es6/01.js --out-file dist1/000001.js

#下面这个命令是上面那个命令的简写
babel es6/01.js -o dist1/000001.js

insert image description here

8.7.2 Transcoding according to folder

Use the following command to complete "transcoding according to folder"

babel es6 --out-dir dist2

#下面这个命令是上面那个命令的简写
babel es6 -d dist2

insert image description here

9. Modularity

9.1 Introduction

Modularization in the backend: When we develop backend interfaces (mapper, service, controller), we inject mapper into service and inject service into controller. In this way, through injection, we can realize that service calls mapper, and controller calls service , that is, calls between different classes are implemented . The mutual calls between classes in the backend are called modular operations

Modularity in the front end: The mutual calling between js and js is called front-end modular operation , for example: if you want to call the method in 000001.js in 01.js, this is called modularization

insert image description here

9.2 es5 implements modular operation

1. Create a moduledemo folder under the workspace, and then use the command npm init -y to initialize the project in the terminal

2. Create a folder es5module under the moduledemo folder, and create files 01.js and 02.js under this folder

insert image description here

3. Define the js method in 01.js for 02.js to call

//1.在01.js中定义js方法供02.js调用
//定义成员:
const sum = function(a,b){
    
    
    return parseInt(a) + parseInt(b)
}
const subtract = function(a,b){
    
    
    return parseInt(a) - parseInt(b)
}

//2.设置哪些方法可以被其他js调用
module.exports = {
    
    
    sum,
    subtract
}

insert image description here

module.exports = {...}Function: These methods of 01.js are equivalent to private methods in java. By default, the methods in 01.js cannot be called in 02.js. Only after adding them module.exports = {...}can they be called by other js

4. Call the method just defined in 01.js in 02.js

//在02.js中调用刚刚在01.js定义的方法
//1.引入01.js文件
const m = require('./01.js')

//2.调用
console.log(m.sum(1, 2))
console.log(m.subtract(10, 3))

insert image description here

  • ./Indicates the directory where the current file is located
  • ../Indicates the upper level directory of the directory where the current file is located
  • We may sometimes omit it when we are learning the backend ., but this must not be omitted, otherwise an error will be reported
  • The parameter of require can be single quotes or double quotes

5. Use the command node 02.js to view the results in the terminal

insert image description here

9.3es6 implements modular operation

9.3.1 The first way of writing

1. Because:If you use the es6 writing method to achieve modular operation, it cannot be run directly in the node.js environment. You need to use babel to convert the es6 code into es5 code before it can run in node.js, the babeldemo folder has already configured the babel transcoder, so, for convenience, our next example will be implemented under the babeldemo folder.

Create a folder modulees61 under the babeldemo folder, and create files 01.js and 02.js under this folder

insert image description here

2. Define methods in 01.js, and set which methods can be called by other js

//在01.js中定义方法,并且设置哪些方法可以被其它js调用
export function getList() {
    
    
    console.log('getList......')
}

export function save() {
    
    
    console.log('save......')
}

insert image description here

3. Call the method just defined in 01.js in 02.js

import {
    
     getList, save } from './01.js'

//调用方法
getList()
save()

insert image description here

  • Single quotes or double quotes after from can be used

4. Convert es6 modular code to es5 modular code

First create a folder modulees611 under the babeldemo folder, and then execute the following command on the terminal to transcode according to the folder

babel modulees61 -d modulees611

insert image description here

5. Use the command node 02.js to view the results in the terminal

insert image description here

9.3.2 The second way of writing

1. Create a folder modulees62 under the babeldemo folder, and create files 01.js and 02.js under this folder

insert image description here

2. Define methods in 01.js, and set which methods can be called by other js

export default {
    
    
    getList() {
    
    
        console.log('getList......')
    },
    save() {
    
    
        console.log('save......')
    }
}

insert image description here

3. Call the method just defined in 01.js in 02.js

import m from './01.js'

//调用方法
m.getList()
m.save()

insert image description here

  • The m here can be understood as an object in java
  • ./01.jsin .jscan be omitted

4. Convert es6 modular code to es5 modular code

First create a folder modulees622 under the babeldemo folder, and then execute the following command on the terminal to transcode according to the folder

babel modulees62 -d modulees622

insert image description here

5. Use the command node 02.js to view the results in the terminal

insert image description here

10.webpack

10.1 Introduction

Webpack is a front-end resource loading/packaging tool. It will perform static analysis based on the dependencies of the modules, and then generate corresponding static resources for these modules according to the specified rules.

Benefits of webpack: Webpack can convert various static resources js, css, and less into a static file, which reduces the number of page requests

10.2 Project initialization

1. Create a webpackdemo folder under the workspace

2. Use the command npm init -y to initialize the project in the terminal

insert image description here

10.3 Install webpack tools (plugins)

Use the following commands to install webpack and webpack-cli (4.41.4 of webpack is the version of the teacher, I really don’t know what version of webpack-cli the teacher uses, and I use the 3.3.2 version based on the principle of not using the latest)

npm install -g [email protected] [email protected]

insert image description here

After the installation is complete, use the following command to check whether the installation is successful

webpack -v
webpack-cli -v

insert image description here

10.4 Create js files for packaging operations

Create a folder src under the webpackdemo folder, and create js files common.js, utils.js, and main.js under src. In these three js files, we plan to: define methods in common.js and utils.js, and then Introduce common.js and utils.js in main.js and call their methods. Next, we write code in these three js files

common.js:

//方法名字是info,这个方法可以被别的js调用
exports.info = function (str) {
    
    
    document.write(str);//在浏览器中输出
}

insert image description here

utils.js:

//方法名字是add,这个方法可以被别的js调用
exports.add = function (a, b) {
    
    
    return a + b;
}

insert image description here

main.js:

//在main.js中引入common.js和utils.js并调用它们的方法
const common = require('./common.js');
const utils = require('./utils.js');
common.info('Hello common!' + utils.add(1, 2));

insert image description here

10.5 js packaging

1. Create a folder dist under the webpack folder to store the packaged files

2. Create the configuration file webpack.config.js in the webpack folder and write the configuration

  • The name of the configuration file is fixed
  • The content in the configuration file is a fixed structure
const path = require("path"); //Node.js内置模块
module.exports = {
    
    
    entry: './src/main.js', //配置入口文件
    output: {
    
    
        path: path.resolve(__dirname, './dist'), //输出路径,__dirname:当前文件所在路径
        filename: 'bundle.js' //输出的文件的名字
    }
}

insert image description here

entry is the program entry, because there are two other files in main.js, so main.js is the program entry, so write ./src/main.js here

3. Use the command to perform packaging operations

webpack #有黄色警告
webpack --mode=development #没有警告
webpack --mode=production #没有警告

The above three commands can perform packaging operations. If you use the first webpackcommand, there will be a yellow warning. The general meaning of the warning is to suggest that you choose the development environment or production environment, that is, it is recommended that you use

command webpack --mode=developmentor webpack --mode=production, here I use the webpack --mode=development command in the terminal to perform the packaging operation. After performing the packaging operation, you will find that there is an additional bundle.js file in the dist folder, which is the packaged file

insert image description here

4. Test

Because we wrote such a line of code in common.js: document.write(str); , this line of code cannot be executed in node.js, and the effect can only be seen in the browser, so the idea of ​​the test step is: create in the webpack folder A 01.html file, and import the js file packaged in step 3 into this file

<script src="dist/bundle.js"></script>

insert image description here

Right click in the blank space and select "Open with Live Server" to see the effect in the browser

insert image description here

insert image description here

10.6 css packaging

1. Create a style.css file under the src folder and write the style content

body {
    
    
    background-color: red;
}

insert image description here

2. Add the following line of code in main.js to introduce the css file created in the previous step

//引入css文件
require('./style.css')

insert image description here

Note: We have said before: because the default is to import js files, it can be omitted .js, for example const common = require('./common'); , but must not be omitted when importing css files.css

3. Webpack itself can only process JavaScript modules. If you want to process other types of files, you need to use loader for conversion. Loader can be understood as a converter between modules and resources.

We need to install related Loader plug-ins: css-loader is to load css into javascript; style-loader is to let javascript know css

Use the following command in the terminal to install the css loading tool ( @1.1.3and @3.4.2to install the same version as the teacher)

npm install --save-dev [email protected] [email protected]

insert image description here

4. Add configuration to the webpack.config.js configuration file

The complete content in the webpack.config.js configuration file:

const path = require("path"); //Node.js内置模块
module.exports = {
    
    
    entry: './src/main.js', //配置入口文件
    output: {
    
    
        path: path.resolve(__dirname, './dist'), //输出路径,__dirname:当前文件所在路径
        filename: 'bundle.js' //输出的文件的名字
    },
    module: {
    
    
        rules: [
            {
    
    
                test: /\.css$/,    //打包规则应用到以css结尾的文件上
                use: ['style-loader', 'css-loader']
            }
        ]
    }
}

The screenshot is as follows (compared to the webpack.config.js configuration written in the second step of "10.5js packaging", some codes have been added, and I have circled the added codes with boxes)

insert image description here

5. Step 3 of "10.5js packaging" generates a bundle.js file under the dist folder, delete this file first, and then execute the packaging operation. Like the third step of "10.5js packaging", there are three commands for you to choose when performing the packaging operation. Here I use the command webpack --mode=development to perform packaging. After performing the packaging operation, you will find that there is an additional bundle.js file in the dist folder, which is the packaged file

insert image description here

6. Right click in the blank space of the 01.html file and select "Open with Live Server" to see the effect in the browser

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/maxiangyu_/article/details/127019673