Front-end Technology 1.1 Course Arrangement 1.2 Front-end Technology Understanding (Understanding below) 1.2.1 Front-end Development History 1.2.2 New Concept Interpretation 1.2.2.1 Node.js 1.2.2.2 Introduction of various front-end frameworks 1.2.2.3 MVVM Model Recognition 1.3 Nodejs & Npm Installation 1.3.1 Installation of NodeJs npm installation in 1.3.2 idea Use of 1.3.3 npm (1) Create common web projects (2) Order learning ECMAScript6 Understanding of 2.1 es6 2.2 es6 common grammar 2.2.1 let&const 2.2.2 Deconstruction Expressions 2.2.3 Arrow Function 2.2.4 Promise 2.2.5 Modular Specification 2.2.5.1 Export Function 2.2.5.2 Import Function III. Introduction to Vue 3.1 What is vue 3.2 el,data and method 3.2.1 Use the Vue Trilogy 3.2.2 Important Elements of Vue el data methods 3.3 vue hook method 3.3.1 vue life cycle 3.3.2 Hook Code 3.4 vue expression IV. vue Important Directives (Sequence Adjustment) 4.1 v-html and v-text 4.2 v-for Use of 4.3 v-bind 4.4 v-model 4.4 v-show&v-if 4.4.1 v-show Case Representation 4.4.2 v-if case 4.5 v-on event binding V. vue Small Functions 5.1 Computation: computed 5.1.1 Calculated directly in the expression 5.1.2 Using Computing Scheme 5.2 watch monitoring attributes VI. Components 6.1 Global Components 6.1.1 Initial Writing 6.1.2 Smoke (same effect) 6.2 Local Components 6.3 Component Module 6.3.1 template tag template 6.3.2 script tag template 6.3.3 External js Routing 8. Web Packing [Understanding] 8.1 Basic Understanding 8.1.1 Packing Understanding 8.1.2 Understanding of webpack 8.2 Install webpack Local installation: Global Installation: 8.3 Preparations 8.3.1 Create a new module project 8.3.2 Initialization Project 8.3.3 Prepare corresponding modules 8.4 Packing Order 8.5 CSS Loading 8.5.1 Loader Installation 8.5.2 a.js introduces equivalent css 8.5.3 webpack.config.js 8.6 Hot Update web Server 8.6.1 Installation Plug-in 8.6.2 Add Startup Script 9. vue_cli (scaffolding) 9.1 Why use vue_cli 9.2 vue_cli Quick Start Other Switching npm mirror Word Learning
Front-end Technology
1.1 Course Arrangement
Know the front end, install NodeJs and npm ES6 Grammar Learning Vue Learning
1.2 Front-end Technology Understanding (Understanding below)
What you can see is the front end, such as web,android,ios, etc.
1.2.1 Front-end Development History
1.2.2 New Concept Interpretation
1.2.2.1 Node.js
Front-end developable back-end (for small applications only) Asynchronous style is popular with developers NPM was first released as a package management system of node.js NPM is a module management tool provided by Node, which can easily download and install many front-end frameworks. Maven is equivalent to our back end
1.2.2.2 Introduction of various front-end frameworks
node-based front-end frameworks have sprung up (as shown below)
## 1.2.2.3 MVVM Model Recognition
M: Model, model, including data and some basic operations V: View, View, Page Rendering Results VM: View-Model, bi-directional operation between model and view (without developer intervention)
Before MVVM, the developer retrieves the required data model from the back end and then renders it into View through DOM operation Model. Then when the user manipulates the view, we need to get the data from the view through DOM, and then synchronize it into the Model. What VMs in MVVM need to do is to encapsulate DOM operations completely. Developers no longer need to care about how Models and Views interact with each other.
As long as our Model changes, it will naturally show up on View. When the user modifies the View, the data in the Model changes as well. Release developers from tedious DOM operations and focus on how to operate Models.
1.3 Nodejs & Npm Installation
Node comes with NPM (npm is available when node is installed)
1.3.1 Installation of NodeJs
Find and download https://nodejs.org/en/download from the official website/ Install it directly after downloading (fool type, no explanation)
Post-installation testing Determine whether there is a node JS configuration in the environment variable Enter the command node-v: View the version of node Enter the command npm-v: View the version of NPM
Enter the command NPM install npm@latest-g to upgrade NPM
npm installation in 1.3.2 idea
Restart idea after installation The Teminal below idea can enter commands
Use of 1.3.3 npm
We have pom.xml in maven and package.json in npm
(1) Create common web projects
(2) Order learning
Initialization command NPM init - > initialization creates a package.json file in the project (equivalent to a maven pom.xml file) NPM init-y - > initialization (jump determination information)
Installation command
Global Installation (available for all projects)
npm install -g vue
Npm-g root installation path
Local Installation (Installation Projects can be used)
npm install/i vue
npm install/i vueimage
Other orders View a module: npm list vue List module (see all modules): npm ls Uninstall module: npm uninstall vue Update module: npm update vue Operating Engineering: NPM run dev/test/online-> Usually run and use (need configuration, can not be implemented now) Compilation Engineering: NPM run build - > needs to be compiled when on-line (compiled and thrown into the server to run)
ECMAScript6
Understanding of 2.1 es6
ECMAScript is the specification of browser scripting language, which can be narrowly understood as the specification of javascript. ES6 is the latest JS grammar Later, more years are used to make versions (ES2017,ES2018,...)
2.2 es6 common grammar
2.2.1 let&const
Let: Used to declare variables. Its use is similar to var (but declared variables are valid only in the block of code where the let command resides. ) Code block is valid No duplicate declaration No variable elevation
/* var Test results are available outside the loop, but let s are not. As you can note, let is more in line with our java definition of a variable */ for (var i = 0; i < 5; i++) { console.debug(i); } console.debug("external i:"+i); //External i:5 for (let j = 0; j < 5; j++) { console.debug(j) } console.debug("external j:"+j); //ReferenceError: j is not defined const:Declarative constants cannot be modified const val = "abc"; val = "bcd"; //invalid assignment to const `val'
2.2.2 Deconstruction Expressions
ES6 allows you to extract values from arrays and objects according to a certain pattern and assign variables, which is called Destructuring. Deconstruction variable assignment
//Previous variable assignment let a = "Zhang San"; let b = "Li Si"; let c = "Wang Wu"; console.debug(a,b,c); //Assignment using deconstruction variables let [a,b,c] = ["Zhang San","Li Si","Wang Wu"] console.debug(a,b,c);
Array Deconstruction
let arr = ["Na Zha","Jin Zha","Mu La"]; let [a,b,c] = arr; console.debug(a,b,c); //Object Deconstruction let person = {name:"Na Zha",age:12}; //Assigning values in person objects to name and age attributes directly by name let {name,age} = person; console.debug(name,age);
2.2.3 Arrow Function
The equivalent of lambda expression in our Java Case 1: Primitive function and arrow function In arrow function, parentheses are parameters and braces are function bodies. If the body of a function has only one sentence, braces can be omitted
//Define ordinary functions function say() { console.debug("I am a Chinese...") } say(); //Define arrow function //It can also be written as: var hi=() => console. debug ("I am a Chinese..."); var hi = ()=>{ console.debug("I am a Chinese...") } hi(); //Case 2 : Functions with parameters function say(name) { console.debug(name); } say("Xiao Zhang"); //Reference in parentheses and function body in parentheses var hi = (name) =>{ console.debug(name); } hi("petty thief");
Case 3: Adding appropriate parameters to the object
var person = { //Writing of ES5 say:function(name){}, //Writing with arrow function say:name=>{}, //Shortest Style - > It was my favorite Style at that time. say(name){} };
Case 3: Mixing Deconstruction with Arrow Function
//Define a variable const person = { name:"Xiao Nazha", age:12 } //Traditional solutions function say(person){ console.debug("name="+person.name); } say(person); //Deconstruction + Arrow Scheme // The parentheses in this place represent the receiving parameters, and the parentheses in the parentheses represent the deconstruction of the passed objects. var hi =({name})=>{ console.debug("name="+name); } hi(person);
2.2.4 Promise
Asynchronous programming solutions (more powerful than traditional solutions) Promise, in short, is a container containing events that will end in the future. We can encapsulate the result of an asynchronous request in Promise Note: In the future, we will use Axios (simpler), which is the underlying packaging of Promise. You can simply understand the difference between our native Ajax and JQuery after packaging.
/** * Create this object directly * @type {Promise<any>} * resolve: Resolve reject: waste; reject; */ var promise = new Promise(function (resolve, reject) { //The corresponding code will be executed in 5 seconds. The module took 5 seconds for our Ajax request. setTimeout(()=> { let number = Math.random(); if(number>0.5){ resolve("Successful Brothers"); }else{ reject("Failed buddies") } },5000) }); //Successfully execute the code in the then and fail to execute the code in the catch promise.then(function (msg) { console.debug(msg); }).catch(function(err){ console.debug(err); })
2.2.5 Modular Specification
Simply understand, with this concept, now this functional browser does not support, we can not test. Modularization is the separation of code, which can be reused. Modularity is an idea that can be realized by many specifications at the front end. Common Js: Implementation Scheme in nodeJS amd/cmd: It can be implemented directly in browser ES6: Can be directly implemented in browsers ES6 Let's use two commands: export and import. export command is used to specify the external interface of the module The Import command is used to import functions provided by other modules
2.2.5.1 Export Function
Derived Generation Code
//Define a variable (object) const util ={ add(a,b){ return a+b; } } //Export this variable (object) export util; //Derived code abbreviations //Direct derivation of corresponding variables export const util ={ add(a,b){ return a+b; } }
You can export anything (basic types, functions, arrays, objects)
var name = "Xiao Zhang"; var age = 34; export {name,age} //Names can be omitted export default { add(a,b){ return a+b; } }
2.2.5.2 Import Function
Import code
//Import util (Note: If the import is a default keyword export, the name of the util is optional) import util from 'hello.js' //Calling methods in util util.sum(3,4)
Batch import
//Batch import the name and age exported earlier import {name,age} from 'user.js' console.debug(name,age);
III. Introduction to Vue
3.1 What is vue
Vue (pronunciation/vju/, similar to view) is a progressive framework for building user interfaces Vue progressive understanding: http://www.bslxx.com/a/vue/2017/1205/1490.html Vue only focuses on the view layer. Vue extends HTML through new attributes (custom) and {expression}}. The goal of Vue is to implement the data binding and composition of the view components of the response through the simplest API possible. Vue is very simple to learn. Characteristics of Vue Light weight The Vue.js library is very small in size and does not depend on other base libraries. Data binding For some front-end UI interfaces with rich interaction and similar state machine, data binding is very simple and convenient. instructions The built-in instructions are unified as (v -*), and you can also customize the instructions. By changing the corresponding expression values, you can modify the corresponding DOM. Plug-in The Vue.js core does not include Router, AJAX, form validation and other functions, but it is very convenient to load the corresponding plug-ins according to needs. Componentization Components can extend HTML elements and encapsulate reusable code. Allow us to build large applications using small, self-contained, and commonly reusable components The History of Vue
Vue is a relatively new technology. Version 1.0 was released in 2014. The author of Vue, Yuyuxi, a former employee of Google, announced that he would join Alibaba as a technical consultant in September 2016. Vue compares other frameworks: https://cn.vuejs.org/v2/guide/comparison.html ad#
3.2 el,data and method
3.2.1 Use the Vue Trilogy
Introducing Vue.js Elements ready to be mounted JS completes mounting
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello vue!!!</title> <!-- ①.Introduce vue Of js file:Yes vue Functional support --> <script src="vuejs/vue.js"></script> </head> <body> <!-- ②.Prepare one div,Use as sum vue Generative relationship --> <div id="app"> {{msg}} </div> <!--③.write js : Let's get ready. div and vue Generative relationship--> <script> new Vue({ el:"#app", data:{ msg:"hello,vue!" } }) </script> </body> </html>
3.2.2 Important Elements of Vue
el
el is used to complete the mounting function Mounting can use id,class, label No matter how you use it, you can only mount one It is recommended to use id for mounting. Only by mounting successful elements can we use vue's functions (expressions, etc.)
data
Data is our data. There are two ways to get data Get / design directly in js To obtain in an expression
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> {{msg}} === {{sex}} <br> {{employee}} === {{employee.name}}=== {{employee.age}} <br> {{hobbys}} === {{hobbys[0]}} </div> <script> var vue = new Vue({ el:"#app", //Data: Represents the corresponding data data:{ msg:"I am a thing.", sex:true, employee:{ name:"Publicize", age:18 }, hobbys:["Play basketball","Write code","Don't write code."] } }) alert(0); //When the data changes, the data in the expression changes at the same time. // vue.msg = I'm not really a thing. vue.msg = "haha" </script> </body> </html>
methods
It refers to our method elements. Location of method invocation Call directly in js Can be invoked with expressions Data can be obtained directly from data using this
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <!--Method can be invoked in an element--> <div id="app"> {{haha()}} {{name}} {{say()}} {{hello("666")}} </div> <script> var vue = new Vue({ el:"#app", //Data: Represents the corresponding data data:{ name:"Wang Fugui", age:25 //You can also write methods in data and call them, but it is not recommended to do so. /* haha(){ alert("Happy..." } */ }, //Corresponding methods methods:{ // Get the data in our data directly in the method say(){ alert("My name is King Quan Fu Gui.") }, hello(msg){ alert(this.name+msg); this.name = "Kingship is precious"; } } }) //Method 1: Direct call //vue.say(); </script> </body> </html>
3.3 vue hook method
Vue instances have a complete life cycle, that is, from the start of creating, initializing data, compiling templates, mounting Dom, rendering update rendering, uninstalling and a series of processes, we call this the life cycle of Vue. In general, Vue instances are created to destroy the process, is the life cycle.
3.3.1 vue life cycle
Each Vue instance is created through a series of initialization processes Create an instance Loading template Rendering Template Vue sets hook functions (listening functions) for each state in the lifecycle The Difference between created and mounted Create: Called before the template is rendered into html, i.e. some attribute values are usually initialized and then rendered into views mounted: Called after the template has been rendered into html, usually after the initialization page has been completed, and then do some necessary operations on the dom node of HTML
3.3.2 Hook Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>I am a hook.</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app">{{msg}}</div> <script> new Vue({ el:"#app", data:{ msg:"xxx" }, //Call before the template is rendered into html created(){ this.msg ="Hello, dear!"; }, //Called after the template is rendered into html, usually after the initialization page is completed, then do some necessary operations on the dom node of HTML mounted(){ this.msg = "No, dear!"; } }) </script> </body> </html>
3.4 vue expression
Writing code in the expression of Vue is the same as js You can use four operators Trinomial operators can be used Strings, objects and arrays can be manipulated directly
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <!-- Expression:{{}} -> Obtain data The data in the file can also be invoked methods Inside the method Perform four mixed operations(Add, subtract, multiply and divide) --> <div id="app"> {{msg}} <br> <!-- Perform four mixed operations(Add, subtract, multiply and divide) --> plus:{{6+4}} <br> <!--Stitching strings--> plus:{{6+"4"}} <br> reduce:{{6-4}} <br> ride:{{"6"*"4"}} <br> except:{{6/4}} <br> except:{{num1/num2}} <br> <hr> <!-- JSin:null,"",NaN,undefined,0,falseRepresentative leave --> Gender:{{sex?"male":"female"}} <hr> <!--String operation(and js equally) substr:How many are intercepted from the number one? substring: From the first to the last toUpperCase()Capitalize --> {{name}} <br /> {{name.length}} <br /> {{name.substr(2,3).toUpperCase()}} <br /> {{name.substring(2,3)}} <br /> <hr> <!--Object operations--> {{employee}} ==== {{employee.name}}==== {{employee.toString()}}<br> {{employee.say()}} <!-- Array operation --> <hr> {{hobbys}} === {{hobbys[0]}} === {{hobbys.length}} </div> <script> new Vue({ el:"#app", data:{ msg:"Have nothing to do", name:"abcdefg", num1:10, num2:5, sex:"", hobbys:["Vehicle","House","money","garbage"], employee:{ name:"Zhang Dian", age:16, say(){ return "I am"+this.name; } } } }) </script> </body> </html>
IV. vue Important Directives (Sequence Adjustment)
Instruction Name, Instruction Function
v-html Display and parse HTML code
v-text
v-for traversal and looping functions traversal numbers, strings, objects, arrays
v-bind Binding Attribute Simple Form: Attribute Name= "Value"
v-model bi-directional binding only supports input,select,textarea
v-show Display and Hide: style = "display=none"
V-IF judgement v-if/v-else-if/v-else
v-on Binding Event @Event Name = Method Name ()
4.1 v-html and v-text
html Will analyseHTMLLabel(Quite:innerHTML) text Not parsingHTMLLabel(Quite:innerText) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <span id="myspan">{{msg}}</span> <!-- Use instruction writing to set data notes:Getting data in instructions does not require writing expressions{{}} --> <span v-html="msg"></span> <span v-text="msg"></span> </div> <!-- instructions:vue A special label is designed. v-Instruction Name --> <script> //Native js stands for adding data to this myspan /** * innerText:It will output the added content as it is (it will not be recognized and compiled as an html tag) * innerHTML: Will identify and compile our html tags */ /* document.getElementById("myspan").innerHTML = "<h1>Oh, for </h1>; document.getElementById("myspan2").innerText = "<h1>Oh, for </h1>; */ new Vue({ el:"#app", data:{ msg:"<h1>Oh, for...</h1>" } }) </script> </body> </html>
4.2 v-for
Traversing through our data (numbers, strings, objects, collections) Numbers are ordinary loops for (var i = 1; i < = number; i +) String is to get every letter. Object loop <span v-for="(v, k, i) in object"></span> v: Attribute values representing objects k: The attribute name representing the object i: Representative Index Array loop <span v-for="(v, i) in array"></span> v: Attribute values representing objects i: Representative Index
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <!--Traversal number for(var i=1;i<=5;i++)--> <ul> <li v-for="v in num">{{v}}</li> </ul> <!--Traversal string:Get each value in the string--> <ul> <li v-for="v in name">{{v}}</li> </ul> <!-- Traversing objects (v) If you write only one value,Acquisition only value Value (v,k) v:yes value The value of the value of the ____________ k:yes key(attribute) (v,k,i) v:yes value The value of the value of the ____________ k:yes key(attribute) ,i: Indexes --> <ul> <li v-for="(v,k,i) in smalltxt">{{k}} - {{v}} -{{i}}</li> </ul> <!--foreach (v,i) : v:Current data values i:Current traversal index --> <ul> <li v-for="(v,i) in hobbys">{{v}}==={{i}}</li> </ul> </div> <script> /** * v-for:Do the corresponding loops (numbers, strings, objects, arrays) */ new Vue({ el:"#app", data:{ num:5, name:"zhang", smalltxt:{ name:"Duoluo Daluo", author:"Yang Ge", sn:"34325Nfe" }, hobbys:["Having dinner","Sleep?","Bean Bean","garbage"] } }) </script> </body> </html>
Use of 4.3 v-bind
Bind is mainly used to bind the corresponding properties < label v-bind: attribute name = "attribute value"> bind has a shorthand form < tag: attribute name = "attribute value"> If the whole object is bound directly by attributes < label v-bind= "object">
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <!-- //standard notation-> v-bind:Property name v-bind:src -> Binding corresponding properties(The values can be obtained from data Chinese Acquisition) //Short form-> :Property name //Multiple Attribute Binding v-bind="object" --> <img v-bind:src="imgUrl" v-bind:height="height" /> <img :src="imgUrl" :height="height" /> <img v-bind="img" /> </div> <script> /** */ new Vue({ el:"#app", data:{ imgUrl:"imgs/1.jpg", height:120, //There are multiple attributes in this object img:{ src:"imgs/1.jpg", height:240, mei:"haha" } } }) </script> </body> </html>
4.4 v-model
It is mainly used to complete two-way binding. Can only be used for: input,select,textarea
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> //Name:<input type="text" v-model="inputVal"> <br> {{inputVal}} <hr> //hobby: <input v-model="checkboxVal" value="1" type="checkbox">Watch movie <input v-model="checkboxVal" value="2" type="checkbox">Read Novels <input v-model="checkboxVal" value="3" type="checkbox">Look at cartoons <input v-model="checkboxVal" value="4" type="checkbox">garbage <br> {{checkboxVal}} <hr> //Gender: <input v-model="radioVal" value="1" type="radio">male <input v-model="radioVal" value="2" type="radio">female <input v-model="radioVal" value="3" type="radio">Chat with others <br> {{radioVal}} <hr> <select v-model="selectVal"> <option value="1">China</option> <option value="2">Japan</option> <option value="3">U.S.A</option> </select> <br> {{selectVal}} <hr> <textarea v-model="textareaVal"></textarea> <br> {{textareaVal}} </div> <script> /** * v-model:Use only in form tags (input,select,textarea) */ new Vue({ el: "#app", data: { inputVal:"I am Yang Yang. Who am I afraid of?!", checkboxVal:["1","3"], radioVal:2, selectVal:2, textareaVal:"sdfsfd" } }) </script> </body> </html>
4.4 v-show&v-if
V-show is used to display and hide < label v-show= "true/false"> V-IF <label v-if= "condition"> < show is just hiding tags, if directly there will be no tags that do not meet the conditions.
4.4.1 v-show Case Representation
The final effect is to have a button, click on the display image, and then click on the hidden image.
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <button onclick="showyishow()" >Spot me.</button> <br /> <!-- v-show:true(display)/fales(No display) //notes:No display( style="display: none;") --> <img src="imgs/1.jpg" v-show="isShow" /> </div> <script> /** * v-model:Use only in form tags (input,select,textarea) */ var vue = new Vue({ el: "#app", data: { isShow:false } }) function showyishow() { vue.isShow = !vue.isShow; } </script> </body> </html>
4.4.2 v-if case
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <!-- if: If the condition is not met, the page does not have this element directly. show:Elements exist, only hidden --> <div v-if="age<18"> Minors are prohibited from entering </div> <div v-else-if="age>=18 && age<60"> Please come in objectively. Welcome here. </div> <div v-else> Old immortals, do not eat human fireworks </div> </div> <script> /** * v-model:Use only in form tags (input,select,textarea) */ var vue = new Vue({ el: "#app", data: { age:10 } }) // alert(0) // vue.age = 89; </script> </body> </html>
4.5 v-on event binding
Event binding can use v-on < tag v-on: event name = method name > Called methods can be exempted from () v-on has a shorthand form < label @ event name = method name >
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vuejs/vue.js"></script> </head> <body> <div id="app"> <!-- //The method here can be executed without parentheses. v-on:Event name="Method name()" @Event name="Method name()" --> <button v-on:click="say()">A little surprise for me...</button> <button @click="hello('Wind Curse')">More of me!!!</button> <button @click="age++">{{age}}</button> </div> <script> var vue = new Vue({ el: "#app", data: { name:"Xiao Ming", age:12 }, methods:{ say(){ alert("Point, you melon doll!") }, hello(msg){ console.debug(this.name+"Look out:"+msg); } } }) </script> </body> </html>
V. vue Small Functions
5.1 Computation: computed
If a value needs a lot of calculation and display, it is recommended to use computational attributes to calculate it first and then use it directly. It is very convenient to use js expression in interpolation expression, and it is often used. Computing attributes is essentially a method, but data must be returned. This method can then be used as a variable in page rendering.
5.1.1 Calculated directly in the expression
<body> <div id="app"> {{ new Date(bronDate).getFullYear() + '-'+ new Date(bronDate).getMonth()+ '-' + new Date(bronDate).getDate() }} </div> <script> new Vue({ el:"#app", data:{ bronDate:1529032123201 //Time millisecond value } }) </script> </body>
5.1.2 Using Computing Scheme
<body> <div id="app"> {{birth}} </div> <script> new Vue({ el:"#app", data:{ bronDate:1529032123201 //Time millisecond value }, computed:{ birth(){// Computing attributes is essentially a method, but results must be returned const d = new Date(this.bronDate); return d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate(); } } }) </script> </body>
5.2 watch monitoring attributes
watch allows us to monitor changes in a value. So we can respond accordingly. For example, let's listen for changes in a text box and then make corresponding advanced queries (Baidu Search)
<body> <div id="app"> <input type="text" v-model="msg" /> </div> <script> new Vue({ el:"#app", data:{ msg:"xxx" }, //Monitor corresponding property changes watch:{ //Functions to be performed after changes msg(newVal,oldVal){ console.debug(newVal,oldVal); } } }) </script> </body>
VI. Components
Custom tags (extraction of duplicate code) Components are divided into global components and local components. Component template s have and can only have one label
6.1 Global Components
6.1.1 Initial Writing
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <!--Define a app,There's our custom label in it.--> <div id="app"> <mytag></mytag> </div> <!--Define a app1,There's our custom label in it.--> <div id="app1"> <mytag></mytag> </div> <script> //Configure the global component, called mytag, which can be used in mounted containers Vue.component("mytag",{ //Keep in mind that there is and can only be one external tag template:"<h1>I am a custom component</h1>" }) //Both containers of the page are mounted new Vue({ el:"#app" }) new Vue({ el:"#app1" }) </script> </body> </html>
6.1.2 Smoke (same effect)
In the future, we see that many other people's code is drawn after the effect, we must be able to understand Oh
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <!--Define a app,There's our custom label in it.--> <div id="app"> <mytag></mytag> </div> <!--Define a app1,There's our custom label in it.--> <div id="app1"> <mytag></mytag> </div> <script> //Define the data displayed in the component let tempStr = "<h1>I am a custom component</h1>"; //Define the configuration of components let tempConfig= {template:tempStr}; //Registration component Vue.component("mytag",tempConfig); //Both containers of the page are mounted new Vue({ el:"#app" }) new Vue({ el:"#app1" }) </script> </body> </html>
6.2 Local Components
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app"> <mytag></mytag> </div> <script> new Vue({ el:"#app", //Local components components:{ mytag:{ template:"<h1>I'm really great.</h1>" } }, data:{ inputVal:"" } }) </script> </body> </html>
6.3 Component Module
6.3.1 template tag template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app"> <mytag></mytag> </div> <!--Prepare template data, and if the template is placed in the mount element, it will be displayed directly--> <template id="mytemp"> <form> User name:<input type="text"> </form> </template> <script> //Get the configuration based on the id of the template let tempConfig = {template:"#mytemp"}; Vue.component("mytag",tempConfig) new Vue({ el:"#app" }) </script> </body> </html>
6.3.2 script tag template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app"> <mytag></mytag> </div> <!-- script Preparing the corresponding data --> <script type="text/template" id="mytemp"> <form> User name:<input type="text" /> </form> </script> <script> let tempConfig = { template:"#mytemp" }; Vue.component("mytag",tempConfig) new Vue({ el:"#app" }) </script> </body> </html>
6.3.3 External js
To use import ES6 grammar here, browsers can not directly support the operation. Our main part is to understand the meaning of the code. This grammar can be used after using the server to run later.
Preparing template code for js
const mytesttag = { template:`<h1>Ha-ha</h1>`, name:"mytesttag" }
Introducing code
new Vue({ el:"#app", components:{ mytesttag:()=>import('./index.js') } })
Routing
8. Web Packing [Understanding]
https://www.webpackjs.com/
8.1 Basic Understanding
8.1.1 Packing Understanding
Packing many small fragmented files into a whole reduces the number of derivative requests in a single page and improves the efficiency of the website. The advanced syntax of ES6 is translated and compiled to be compatible with older browsers. The code is packaged and confused at the same time to improve the security of the code.
8.1.2 Understanding of webpack
Webpack is a front-end resource loading/packaging tool. It will do static analysis according to the dependencies of the modules, and then generate the corresponding static resources according to the specified rules.
From the figure, we can see that Webpack can convert various static resources js, css, less into a static file, reducing page requests. Next, we will briefly introduce the installation and use of Webpack.
8.2 Install webpack
Here's how to choose global installation for later use
Local installation:
npm install webpack --save-dev
npm install webpack-cli --save-dev
Global Installation:
Because of the network problem, the installation time may be longer, or even fail. You can do it several times in many ways.
npm install -g webpack
npm install -g webpack-cli
8.3 Preparations
8.3.1 Create a new module project
8.3.2 Initialization Project
Enter the web package test Enter the command NPM init-y
8.3.3 Prepare corresponding modules
a.js
var a= "a Modular"; //Here's the equivalent of introducing a file called b.js var b = require("./b.js"); console.debug(a,b);
b.js
//Definition returns, returning any data define(function(){ var b ="b Modular"; return b; })
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--Introduce a Of js file--> <script src="js/a.js"></script> </head> <body> </body> </html>
Because there are many new grammars that browsers don't support now, there are usually errors in running here.
8.4 Packing Order
Enter the packing command webpack src/a.js-o dist/bundle.js
Modify js introduction
<!--Introduce a Of js file--> <script src="dist/bundle.js"></script>
js configuration file packaging
webpack.config.js, which is in the same directory as the project root
//Provide a good module, regardless of it, here you need to use this module var path = require("path"); // module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), filename: 'bundle.js' } }
8.5 CSS Loading
Default packaging only packages js If you need to package other resource files, you need to download the corresponding loader separately.
8.5.1 Loader Installation
npm install style-loader --save-dev
npm install css-loader --save-dev
8.5.2 a.js introduces equivalent css
var a= "a Modular"; //Here's the equivalent of introducing a file called b.js var b = require("./b.js"); console.debug(a,b); require("../css/index.css");
8.5.3 webpack.config.js
var path = require("path"); //For an output of a module module.exports = { ... //Configure the corresponding packer module: { rules: [ //Configured with support for css, style: style parser css: style loader { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] } }
8.6 Hot Update web Server
It's too cumbersome to repackage every change webpack provides us with a plug-in to run web services and load the latest results
8.6.1 Installation Plug-in
npm install webpack-dev-server --save-dev
8.6.2 Add Startup Script
Configure script in package.json
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --inline --progress --config ./webpack.conf.js" } inline: Automatic refresh - hot: thermal loading Port: Specified port open: open automatically in the default browser - host: You can specify the server's ip, but not 127.0.0.1
9. vue_cli (scaffolding)
Official website: https://github.com/vuejs/vue-cli
9.1 Why use vue_cli
In development, there are many files that need to be packaged (html,css,js, pictures,...) vue provides scaffolding to quickly build web engineering template Global Arrangement Command (which will be used by many projects in the future): NPM install-g vue-cli
9.2 vue_cli Quick Start
New module
Enter the catalogue
D:\code\ideawork\vue-02>cd 02vueclitest
D:\code\ideawork\vue-02\02vueclitest>
Create a webpack project Command: vue init webpack: initialization Command: npm run dev: run directly
npm run build packages can run on servers Error Resolution Delete node_modules from the project Find vue-cli in everythink and delete it If not, copy other students'node_modules directly and use them.
Other
Switching npm mirror
Global Installation nrm: NPM install nrm-g View mirror source nrm ls Switching Taobao Mirror Source nrm use taobao
Word Learning
Promise:Commitment agreement(Asynchronous programming[ ajax]) data:data methods:Method(Multiple methods) el(element):element created mounted: Installed(When ready) import:Import export:export