Big front-end related - nodejs to vue

I. Introduction

  At present, it is often said that the front and back ends are separated, and the front end also has a bunch of magical technologies. Some things that only the back end can do, the front end can also do (such as connecting to the database). Faced with some small systems, front-end engineers can handle the entire system. The jsp I learned before seems to have no practical use. Here, Node.js is used as the entry point to simply learn about the big front end.

Two, vscode installation

1. Install

Go directly to the official website to download vscode
vscode official website
Baidu Encyclopedia:
  Visual Studio Code (referred to as "VS Code") is Microsoft's official announcement at the Build Developers Conference on April 30, 2015 that it runs on Mac OS X, Windows and Linux. A cross-platform source code editor for writing modern web and cloud apps that runs on the desktop and is available for Windows, macOS and Linux. It has built-in support for JavaScript, TypeScript, and Node.js, and has a rich ecosystem of extensions for other languages ​​(such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and Unity).

2. Simple operation of vscode

CTRL+P		搜索(配置/...)
>Configure Display Language		切换语言配置		在搜索中输入(后面一样)
>font		字体大小等设置
或者:
文件-->首选项-->设置-->font	 大概中间有关font size 直接调整
文件-->首选项-->设置-->emment	打开TAB自动补齐(默认打开)
!				!自动生成基本html格式

3. Node.js

1. Install

  Install your own computer needs to download from the official website: official website
fool-style installation, automatically configure environment variables, and now integrate npm.

2. The test installation is successful

Enter directly in the cmd terminal:

node -v		查看版本号---测试是否安装成功
npm -v		查看包管理器版本(npm包管理器,后面说)

Many installations can use -v or -version to view the version to verify whether the installation is successful

3. Easy to use

Create a new httpserver.js file with vscoe – web page response

//导入模块是require就类似于import java.io
const http=require("http");

//1.创建一个httpserver服务
http.createServer(function(request,response){
    
    
    //浏览器怎么认识hello server!!
    //下面这行告诉浏览器将以text-plain(文本)去解析hello server这段数据
    response.writeHead(200,{
    
    'Content-type':'text/html'});//text/html是html格式(即<strong>会翻译成标签)
    //给浏览器输出内容
    //2.监听一端口8888
    response.end("<strong>hello server!</strong>");
}).listen(8888)
console.log("你启动的服务是:http://localhost:8888已启动成功");

//3.启动服务 终端输入node httpserver.js
//4.在浏览器访问http://localhost:8888

4. Front-end connection database

Terminal input: nmp install mysql —— install the mysql operation module of nodejs
After installation, three files node_modules, package-lock.json and package.json will appear

Create a new db.js file

//导入mysql依赖包,mysql属于第三方的模块就类似于java.sal
var mysql=require("mysql");

//1.创建一个mysql的Connection对象
//2.配置数据连接的信息
var connection=mysql.createConnection({
    
    
    host:"127.0.0.1",
    user:"root",
    port:3306,
    password:"root",
    database:"testdb"//连接testdb数据库
});
//3.开辟连接
connection.connect();
//4.执行curd
connection.query("select * from _user",function(error,results,fields){
    
    
    //如果查询出错,直接抛出
    if(error)throw error;
    //查询成功(网页打开console查看数据)
    console.log("results = ",results);
});
//5.关闭连接
connection.end();

//最后一步:运行node db.js查看效果

Four, ES6 syntax

1. What is ES6

 Before writing html, jsp var and so on are all ECMAScript5 syntax. If you have written with idea, you should find that idea always wants you to replace var with let or const. ECMAScript6 is a must for big front-ends. Here is a brief introduction to learning.
Baidu Encyclopedia:
 ECMAScript 6 (ES6 for short) is a JavaScript language standard officially released in June 2015, officially named ECMAScript 2015 (ES2015). Its goal is to make the JavaScript language can be used to write complex large-scale applications and become an enterprise-level development language.
In addition, in some cases, ES6 also refers to the new features of ES2015 and later, although later versions should be called ES7, ES8, etc.

2. let and const

The code only has the <body> part, use ! Auto-generated template

    <script>
        //传统定义变量和常量的方式 统一使用var
        var name="张三";
        var link="https://www.baidu.com";
        var PI=Math.PI;
        console.log(name);
        console.log(link);
        console.log(PI);        
        //ES6定义方式
        let name2="李四";
        let link2="https://www.baidu.com";       
        //定义常量
        const PI2=Math.PI;
        console.log(name2);
        console.log(link2);
        console.log(PI2);
    </script>
    <script>
        //let 和const解决var的变量穿透问题,和常量修改的问题
        for(var i=0;i<5;i++){
    
    
            console.log(i);
        }
        //变量穿透,输出5,let会报错
        console.log(i);
        //var定义常量可以被修改,const定义的常量修改会报错
        var PI=Math.PI;
        PI=100;
        console.log(PI);
        //在实际开发和生产中,如果是小程序,unipp或者是一些脚手架中,可以大胆的去使用let和const
        //但是如果在web开发中,建议还是使用var,因为在一些低版本的浏览器还是不支持let和const        
    </script>

3. Template strings

    <script>
        //字符串会牵涉到动态部分
        var person={
    
    
            name:"张三",
            address:"天津码头",
            target:"福记商铺"
        }
        let address="传统的--我是"+person.name+",在"+person.address+"抬货到"+person.target;
        console.log(address);

        //ES6的模板字符串语法
        let address2=`ES6--我是${
      
      person.name},在${
      
      person.address}抬货到${
      
      person.target}`;
        console.log(address2);

    </script>

4. Function default parameters

    <script>
        //函数默认参数
        function sum(a,b){
    
    
            return a+b;
        }
        var result=sum(100,200);    //300
        var result=sum(100);        //NaN  ---sum(100,undefined);
        console.log("result = "+result);

        //但是可以在定义函数给默认值解决这个问题
        function sum2(a=100,b=200){
    
    
            return a+b;
        }
        var result=sum2(400);        //600
        console.log("result = "+result);
    </script>

5. Arrow functions

    <script>
        //箭头函数 - 重点(在未来的项目开发中:比如小程序,unipp,一些常见的脚手架大量使用)
       
        //原来函数
        var sum=function(a,b){
    
    
            return a+b;
        }
        //箭头函数改进--1
        var sum2 = (a,b)=>{
    
    
            return a+b;
        }
        //箭头函数改进--2
        var sum3= (a,b)=>a+b;
        console.log(sum(100,200));
        console.log(sum2(100,200));
        console.log(sum3(100,200));
        //通过上面的列子找到的规律
        //1:去掉function 
        //2.在括号后面加箭头
        //3.如果逻辑代码中仅有return可以直接省去。(如果有逻辑体,就不能省略)
        //4.如果参数只有一个,括号也可以省去(自然多个参数必须加括号)
        var sum4 = (a,b) =>{
    
    
            var num=a+b;
            return num;//不能省略
        }
        //var sum5 = (a,b)=>a+b;
        
        //例子
        var arr=[1,2,3,4,5,6];
        var arrNew=arr.map(function(obj){
    
    
            return obj*2;
        });
        console.log(arrNew);
        //箭头函数简化
        var arrNew2=arr.map(obj=>obj*2);
        console.log("箭头函数简化数组乘二:"+arrNew2);
    </script>

6. Object initialization shorthand and case analysis

    <script>
        //原本
        var info={
    
    
            title:"天津狗不理",
            goods:"包子",
            go:function(){
    
    
                console.log("卖包子");
            }
        };
        console.log("原本对象"+info);

        //es6简写
        //对象是key:value
        //如果key和变量名一致,可以只定义一次
        //如果value是一个函数,可以把`:function`去掉,只剩下()即可
        var title="天津狗不理";
        var goods="包子";
        let info2={
    
    
            title,
            goods,
            go(){
    
    
                console.log("卖包子");
            }
        };
        console.log("ES6简写对象:"+info2);
        console.log("ES6简写对象:"+info2.title);
        console.log("ES6简写对象:"+info2.goods);
        console.log("ES6简写对象:"+info2.go());//这里会先执行info2.go(),下一行返回ES6简写对象:undefined
        
    </script>

example:

    <form action="">
        <p>账号:<input type="text" id="account"></p>
        <p>密码:<input type="text" id="password"></p>
        <p><input type="button" value="登录" id="loginbtn"></p>
    </form>

    <script>
        $("#loginbtn").onclick(function(){
    
    
            var account=$("#account").val();
            var password=$("#password").val();
            //执行异步请求
            // $.ajax({
    
    
            //     type:"post",
            //     url:"xxx",
            //     data:{account:account,password:password},
            //     success:function(){
    
    
                    
            //     }
            // });

            //简写
            var params={
    
    account,password};
             $.ajax({
    
    
                type:"post",
                url:"xxx",
                data:params,
                success(){
    
    
                    
                }
            });
        });
    </script>

7. Object Deconstruction

    <script>
        //对象key:value存在,获取对象属性和方法的方式有两种
        //1.通过.
        //2.通过[]

        var title="天津狗不理";
        var goods="包子";
        let info2={
    
    
            title,
            goods,
            go(){
    
    
                console.log("卖包子");
            }
        };

        console.log("通过.方式--------------------");
        //通过.
        console.log(info2.title);
        console.log(info2.goods);
        info2.go();

        console.log("通过[]方式-----------------");
        //通过[]的方式
        console.log(info2["title"]);
        console.log(info2["goods"]);
        info2["go"]();

        console.log("ES6获取属性和方法的方式-----------------");
        //ES6获取属性和方法的方式(es6对象解构--其实就是快速获取属性和方法的一种形式)
        var {
    
    title,goods,go}=info2;
        //还原代码
        // var title=info2.title;
        // var goods=info2.goods;
        console.log(title,goods);
        go();
    </script>

8. Object spread operator

    <script>
        //对象传播操作符...
        var person={
    
    
            name:"张三",
            address:"天津码头",
            evetnt:"抬杠",
            nickname:"钢三",
            go(){
    
    
                console.log("抬杠抬到力能扛鼎");
            }
        };

        //解构
        var {
    
    name,address,...person2}=person;
        console.log(name);
        console.log(address);
        console.log(person2);
    </script>
    <script>
        //java----后台
        //数据格式: var userPage={pages:10,user:[{},{}],pageNo:1,pageSize:100,total:100};
        //异步请求
        //$.post("/user/search",funtion(res){
    
    
            var userPage={
    
    pages:10,user:[{
    
    },{
    
    }],pageNo:1,pageSize:100,total:100};
            var {
    
    users,...userPage2}=userPage;
            
        // })

    </script>

9. ArrayMap

    <script>
        //要对arr数组每个数组*2
        let arr=[1,2,3,4,5,6,7];
        //传统方式
        let newarr=[];
        for(let i=0;i<arr.length;i++){
    
    
            newarr.push(arr[i]*2);
        }
        console.log(newarr);  
        
        //map
        let newArr2=arr.map(ele=>ele*2);
        console.log("map实现数组*2:"+newArr2);

        //map处理对象的数据
        var user=[{
    
    age:10,name:"珂赛特"},{
    
    age:10,name:"洛丽塔"},{
    
    age:18,name:"吉普赛"}];
        let newUser=user.map(function(ele){
    
    
            ele.age +=1;
            return ele;
        });
        // let newUser=user.map(ele=>ele.age += 1);//这个只返回年龄
        console.log(newUser);

    </script>

10. Array reduce

    <script>
        let arr=[1,2,3,4,5,6,7,8,9,10];
        let result=arr.reduce((a,b)=>a+b);
        console.log("result:"+result);
        //原理:a=1 b=2 result=3
        //a=3 b=3 result=6
        //....
        //a=45 b=10 result=55
    </script>

11. nodejs and <\script>

Create a new 01.js file, just take the above code and put it in

//字符串会牵涉到动态部分
var person={
    
    
    name:"张三",
    address:"天津码头",
    target:"福记商铺"
}
let address="传统的--我是"+person.name+",在"+person.address+"抬货到"+person.target;
console.log(address);

//ES6的模板字符串语法
let address2=`ES6--我是${
      
      person.name},在${
      
      person.address}抬货到${
      
      person.target}`;
console.log(address2);

Run in the terminal:
node .\01.js
The result is the same
Syntax functions in <script> in html can be directly used in nodejs

5. npm

1 Introduction

Npm is equivalent to Maven NPM at the back end
: Node Package Manager
, so there is also a corresponding warehouse: Just search directly on the official website
https://www.npmjs.com/

2. Function

1. Quickly build nodejs projects
2. Quickly install and depend on third-party modules. For example: npm install mysql redis, etc.

3. Initialize the project

终端运行:>npm init 初始化
名称默认回车
版本:可以自己指定eg:1.0.1
描述:我是一个node工程
入口函数:默认index.js回车就行
测试命名---不需要回车就行
仓库地址(git repository)---如果不需要回车就行
关键词  自定义node
作者    自定义person
回车确认

Get the package.json file, the contents of which are as follows:

{
  "name": "3npmpro",            //工程名
  "version": "1.0.1",           //版本
  "description": "我是一个node工程",   //描述
  "main": "index.js",           //入口js
  "scripts": {                  //运行脚本
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node"
  ],
  "author": "person",           //开发者
  "license": "ISC"              //授权协议
}

Similar to the pom.xml file, the role of management depends on
us. When we test, we can also directly enter npm init -y in the terminal to initialize by default.

4. Introduction to installing and uninstalling modules

Quickly install and depend on third-party modules
Terminal:

npm init -y     全部默认参数完成初始化(生成package.json)
npm install mysql   (node_modules和package-lock.json)(mysql在node_modules下的mysql)
npm i redis         (redis也在在node_modules下)

Does express install depend on third-party modules?

npm install xxx or npm i xxx module name
The installation module is placed in the node_moudules folder of the project

Use modules:

- require
//导入模块redis
const redis = require("redis");
//导入mysql
const mysql=require("mysql");

xx.js file:

//导入模块redis
const redis = require("redis");
//导入mysql
const mysql=require("mysql");

const client =redis.createClient();
client.on("error",function(error){
    
    
    console.error(error);
});

client.set("key","value",redis.print);
client.get("key",redis.print);

Uninstall the module:

npm uninstall vue jquery

5.package.json file

package.json file:

"dependencies": {
"mysql": "^2.18.1",
"redis": "^3.1.2"
}

Dependencies downloaded through npm install xxx will be recorded in the package.json file, which is similar to
the role of pom.xml records in maven: reuse
If you create a new project, you can copy the package.json file to a new directory , then open the cmd in the current directory, and enter "npm install" to download all configurations recorded in package.json

6.cnpm

Like Maven, the warehouse is abroad, and the domestic download is slow.
You can use the domestic Taobao mirror cnpm:
to install:

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm -v View cnmp version information

6-2 An error occurred when installing cnpm

If you get the following error:
C:\Users\Lenovo\AppData\Roaming\npm\cnpm.ps1 because running scripts is forbidden on this system.
solution:

	1.在win10 系统中搜索框 输入 Windows PowerShell,选择 管理员身份运行
	2.使用,win+R打开了powershell命令行之后,输入set-ExecutionPolicy RemoteSigned,
然后更改权限为A,最后通过 get-ExecutionPolicy 查看当前的状态
总结:powershell打开后输入:set-ExecutionPolicy RemoteSigned 回车;A 回车;get-ExecutionPolicy 回车。

Six, babel

1. Introduction and function

Function: used to change the es configuration (many browser configurations are not high enough, it can be used to transcode es6 into es5)

2. Install

cmd terminal input:

cnpm install -g babel-cli       安装(-cli默认安装到c盘)
babel --version             查看版本

3. use

Create a new folder, terminal input:
npm init -y initialization
Create a new file /src/example.js (file to be transcoded)

//es6
let name = "张三";
const address = "西安";
let arr=[1,2,3,4,5];
let newArr=arr.map(a=>a*2);
console.log(name);
console.log(address);
console.log(newArr);

Create a .babelrc file in the root directory (babel configuration – what version to convert to – here is es2015)

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

Terminal executes:

babel src -d dist

Errors generally occur here:

Couldn't find preset “es2015” relative to directory “E:\XXX\XXX\5babel”
is because es2015 is not installed

Terminal executes:

cnpm install babel-preset-es2015 --save-dev
appears node_modules file

Perform conversion again:
babel src -d dist
(dist/example.js (es2015 version) appears) (transcode the file under src to the dist file)
js file after transcoding:

"use strict";//使用严格模式,严格模式下你不能使用未声明的变量。

//es6
var name = "张三";
var address = "西安";
var arr = [1, 2, 3, 4, 5];
var newArr = arr.map(function (a) {
    
    
  return a * 2;
});
console.log(name);
console.log(address);
console.log(newArr);

ps: New project installation also copies package.json to a new folder and executes: npm install

4. Custom script

Here is a brief mention of custom scripts. After we download projects from the Internet, we usually enter npm run dev in the terminal to run the project because of the custom scripts.
Add the script in the package.json file:
source file:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

After modification:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev":"babel src -d dist"
},

Terminal execution:
npm run dev
automatically executes

7. Modularization

1 Introduction

The front end is becoming more and more complex, so a mechanism similar to java package (import) and modularization specifications have also been produced. Here is a mention of the CommonJS modular specification and the ES6 modular specification

2. CommonJS modular specification

Export file:

//工具类
const sum = ((a,b)=>a+b);
const sub = ((a,b)=>a-b);
const mul = ((a,b)=>a*b);
const di = ((a,b)=>a/b);
//如何导出给别人使用
module.exports={
    
    
    sum,
    sub,
    mul,
    di
}

Import test (similar to java's import class, which can be used directly after import):

//require
const m=require('./四则运算.js');
console.log(m.sum(4,2));
console.log(m.sub(4,2));
console.log(m.mul(4,2));
console.log(m.di(4,2));

3. ES6 modular specification (commonly used)

Create a new file src/userApi.js (export file):

export function getList(){
    
    
    //在真实业务中,异步获取数据
    console.log("获取数据列表");
}

export function save(){
    
    
    //在真实业务中,异步获取数据
    console.log("保存数据");
}

Create a new file src/userTest.js (import test file):

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

getList();
save();
//默认不支持es6语法

If you execute userTest and report an error

<!-- import {getList,save} from './userApi.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module -->
//默认不支持es6语法

Solution:

npm init -y     先初始化
新建.babelrc文件      转码配置
cnpm install babel-preset-es2015 --save-dev    安装es2015依赖
在package.json文件新建脚本
"build":"babel src -d dist"
终端:npm run build
node .\dist\userTest.js 成功运行

4. The common way of writing es6 (improved version of 3)

Create a new file src/userApi.js (export file):

export default{
    
    
    getList(){
    
    
        //在真实业务中,异步获取数据
        console.log("获取数据列表");
    },

    save(){
    
    
        //在真实业务中,异步获取数据
        console.log("保存数据");
    }
}

Create a new file src/userTest.js (import test file):

import user from './userApi.js'

user.getList();
user.save();

8. Webpack

1 Introduction

Webpack is a module packager that can convert various static resources js, css, and less into a static file for displaying your content.

2. Install

cnpm install -g webpack webpack-cli
webpack -v      查看版本

3. Test js packaging steps

Test: In the src/ folder - main.js imports util.js and common.js files
1 "Create a nodejs project npm init -y
2" Create a src directory
3" Store two util.js that need to be merged in src and common.js
util.js files:

//相加函数
exports.add=(a,b)=> a+b;
//动态增加的相减函数
exports.minus=(a,b)=> a-b;

common.js file:

//输出例子
exports.info=function(str){
    
    
    console.log(str);
    document.write(str);
}

4》Prepare an entry file main.js, in fact, the module is concentrated to import
the main.js file:

//导入util和common
const util =require("./util");
const common =require("./common");

common.info("Hello World ,"+util.add(100,100));
document.write("<br />")
common.info("Hello World ,"+util.minus(100,50));

5 "Define a webpack.config.js file in the root directory to configure the packaging rules

//导入path模块"path"是nodejs的内置模块
const {
    
     dirname } = require("path");
const path=require("path");

//定义JS打包的规则
module.exports={
    
    
    //入口函数:从哪里开始进行编译打包
    entry:"./src/main.js",
    //编译成功以后把内容输出到哪里去
    output:{
    
    
        //定义输出指定目录      __dirname当前目录根目录,产生一个dist文件
        path:path.resolve(__dirname,"./dist"),
        //定义合并的文件名
        filename:"bundle.js"
    }
}

6" Execute webpack to view the effect
Terminal input:

webpack         打包开始
webpack -w      动态监视打包

4. Test Css packaging

The old version of Webpack itself can only process JavaScript modules by default. If you want to process other types of files, you need to use the loader to convert them
.
Create any style.css file in the directory

body{
    
    
    background: yellow;
}

1》Install the relevant loader plug-in first

cnpm install --save-dev style-loader css-loader

2》Configure in webpack.config.js

//导入path模块"path"是nodejs的内置模块
const {
    
     dirname } = require("path");
const path=require("path");

//定义JS打包的规则
module.exports={
    
    
    //入口函数:从哪里开始进行编译打包
    entry:"./src/main.js",
    //编译成功以后把内容输出到哪里去
    output:{
    
    
        //定义输出指定目录      __dirname当前目录根目录,产生一个dist文件
        path:path.resolve(__dirname,"./dist"),
        //定义合并的文件名
        filename:"bundle.js"
    },
    module:{
    
    
        rules:[{
    
    
            test:/\.css$/,      //把项目中所有的.css结尾的文件打包
            use:["style-loader","css-loader"]
        }]
    }
}

3》Import css in main

require("./style.css");

4" execute webpack

九、View-element-admin

Introduction (official):
vue-element-admin is a back-end front-end solution based on vue and element-ui. It uses the latest front-end technology stack, built-in i18n internationalization solutions, dynamic routing, authority verification, refines typical business models, and provides rich functional components. It can help you quickly build enterprise-level mid-background product prototypes. I believe that no matter what your needs are, this project can help you.
Download source code: source code address
preview: preview address

Just take a look, and I will write a separate article about vue later.

Guess you like

Origin blog.csdn.net/youxizaixian123/article/details/121412281