1. Vue overview
Objective: MVVM mode, application characteristics, Vue concept
Summary:
MVVM simplifies front-end operations by bi-directional binding of views and models. Vue is a front-end progressive framework, which can improve the efficiency of front-end development.
2. Construction example project
Objective: create a sample project using IDEA and download vue.com through npm installation in the project js
analysis:
vue is a front-end framework, which is actually a js file; Download vue js file and introduce the js file in the page.
vue.js download method:
- You can refer to vue.com online js;
- You can download vue.com offline js;
- npm package resource manager, you can download Vue js
Summary:
The vue module is installed using npm:
#initialization npm init -y #Download vue module npm install vue --save
3. Demonstrate two-way binding and event handling
Goal: create 01 demo HTML page and initialize Vue instance. Modify Vue data through console to achieve two-way binding effect and create button to achieve click and click self increment
analysis:
- Create a page and initialize vue;
- {obtain display data;
- v-model realizes bidirectional binding;
- v-on demo event handling
Summary:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vuejs test</title> <script src="node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="num"><button v-on:click="num++">Point me</button> <h2>{{name}} Very cool! have{{num}}A subject.</h2> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ name:"dark horse", num: 1 } }); </script> </body> </html>
4. Vue instance life cycle and hook function
Objective: to understand the Vue instance life cycle, the hook function of the life cycle and the common scenarios of the created function
analysis:
When creating a vue instance, you can specify the template id, data, and method; If you need to perform some other operations in the process of instantiation and template rendering; Then you can use the hook function.
Summary:
The hook function will be called automatically at each life cycle stage of the vue instance; Specifically: beforeCreate, created,beforeMount,mounted,updated,beforeUpdate, destroyed, beforeDestroy
Common scenarios of the created hook function: used to initialize data
Hook functions should not be written as arrow functions.
5. Interpolation, v-text and v-html
Objectives: interpolation usage scenarios and requirements; The role of v-text and v-html
Summary:
Interpolation can be used in places where vue instance data need to be displayed, and the data attributes and functions of the instance can be invoked in the interpolation expression.
Functions of v-text and v-html: data can be displayed in the template; Difference: v-html renders the HTML tags appearing in the content, while v-text outputs the content to the element as general text.
6. Instruction - v-model use
Objective: to use the v-model instruction to realize the bidirectional binding of check boxes
Summary:
<div id="app"> <input type="checkbox" value="Java" v-model="language">Java<br> <input type="checkbox" value="Python" v-model="language">Python<br> <input type="checkbox" value="Swift" v-model="language">Swift<br> <h2> You chose:{{language.join(",")}} </h2> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ language:[] } }); </script>
When multiple checkboxes correspond to a model, the type of model is an array, and the value of a single checkbox is of boolean type
The value corresponding to radio is the value of input
By default, the model corresponding to input and textarea is a string
select single selection corresponds to string, and multiple selection corresponds to array
7. Instruction -v-on use
Objective: to understand the syntax of v-on instruction and realize the increment and decrement after clicking the button
analysis:
Before using vue; Page labels can respond to events by setting onXXX; In vue, you can respond to events through v-on instructions.
Summary:
Use of v-on:
<div id="app"> <button v-on:click="num++">increase</button> <button @click="decrement">reduce</button> <h2> num = {{num}} </h2> <hr> Event bubble test:<br> <div style="background-color: lightblue; width:100px;height:100px" @click="print('div It was clicked')"> <button @click.stop="print('Click button')">Let me try</button> </div> <br>Block default events:<br> <a href="http://www.itcast. Cn "@ click. Prevent =" print ('clicked the hyperlink ') "> wisdom Podcast</a> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ num:1 }, methods: { //Diminishing decrement(){ this.num--; }, //Print print(str){ console.log(str); } } }); </script>
Event modifier: syntax v-on:xxxx Modifier. Common modifiers are:
. stop: prevent event bubbling
. prevent: prevents default events from occurring
. capture: use event capture mode
. self: only the event triggered by the element itself is executed. (neither bubbling nor trapping is performed)
. once: execute only once
8. Instruction v-for use
Objective: to understand the v-for instruction syntax and realize the traversal of arrays and objects
analysis:
Implementation: you can specify the data to be traversed when vue is instantiated, and then traverse the display data in the template through the v-for instruction. Generally, the data to be traversed can be obtained by sending asynchronous requests through the hook function created.
Summary:
You can use v-for to traverse arrays and objects:
<div id="app"> <ul> <li v-for="(user, index) in users" :key="index"> {{index}}--{{user.name}}--{{user.age}}--{{user.gender}} </li> </ul> <hr> <ul> <li v-for="(value, key, index) in person"> {{index}}--{{key}}--{{value}} </li> </ul> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ users:[ {"name":"dark horse","age":13,"gender":"male"}, {"name":"Intelligence Podcast","age":13,"gender":"female"}, {"name":"Kuding fish","age":4,"gender":"male"} ], person:{"name":"Chuan Zhihui","age":13,"gender":"male","address":"China"} } }); </script>
If you need to use index numbers during traversal, you can add a parameter at the position of circular traversal; The index number starts at 0.
9. Instructions - v-if and v-show use
Objective: tell the difference between v-if and v-show; Through the click of a button, the display of traversal array results is realized, and v-if is used to judge and process the data in the traversal process; Realize the hiding of text content
analysis:
- v-if: through the click of a button, the display of traversal array results is realized, and v-if is used to judge and process the data during traversal
- v-show: hiding text content
Summary:
v-if elements do not exist when conditions are not met; When the v-show condition is not satisfied, only the element is hidden.
10. Instruction - v-bind use
Objective: to understand the syntax and function of v-bind; Click different buttons to switch different attribute values; Use the special usage in the class attribute to implement a button to switch the background color
analysis:
If you do not want to write the values of src and height, but want to obtain the data attribute values in the vue instance; That can be achieved by using v-bind:
<img v-bind:src="vue Data property name in the instance" :height="vue Data property name in the instance"/>
Summary:
You can use v-bind:
<div id="app"> <button @click="color='red'">gules</button> <button @click="color='blue'">blue</button> <div :class="color"> Click the button to change the background color </div> <hr> <br> <button @click="bool=!bool">Click me to change the color of the color block below</button> <div :class="{red:bool, blue:!bool}"> Click the button to change the background color </div> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ color:"red", bool:true } }); </script>
Function of v-bind: the data of vue instance can be set for the attributes of all elements.
11. Use of calculation attributes
Objective: to calculate the application scenario of attributes and convert a date and time value into yyyy MM DD format string
analysis:
If the millisecond value of a date is to be displayed as a formatted (yyyy MM DD) date string; You can use the method in the calculated calculation attribute for processing.
Summary:
Application of calculated attributes:
<div id="app"> <h2> Your birthday is: {{new Date(birthday).getFullYear()}}-{{new Date(birthday).getMonth()+1}}-{{new Date(birthday).getDay()}} </h2> <hr> <h2> Your birthday is: {{birth}} </h2> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ birthday:1429032123201 }, computed:{ birth(){ const date = new Date(this.birthday); return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDay(); } } }); </script>
Application scenario of computed calculation attribute: it can be applied when interpolation or instruction representation is complex. Some attribute data can be returned after being processed by methods.
12. watch basic and depth monitoring
Objective: usage scenario of watch; And use it to listen for changes in simple attribute values and attribute values in their objects
analysis:
Data attribute in vue instance; Changes due to changes in the page; The values before and after the change can be obtained through watch monitoring.
If it is a modified object data attribute, you can enable depth monitoring to obtain the latest modified object data. For example: person name
Summary:
You can use watch to monitor data attributes as follows:
<div id="app"> <input type="text" v-model="message"> <hr><br> <input type="text" v-model="person.name"><br> <input type="text" v-model="person.age"><button @click="person.age++">+</button> <h2> Name:{{person.name}};Age:{{person.age}} </h2> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ message:"dark horse", person:{"name":"heima", "age":13} }, watch:{ message(newValue, oldValue){ console.log("New value:" + newValue + ";Old value:" + oldValue); }, person: { //Turn on depth monitoring; Changes in attribute values in monitoring objects deep: true, //You can get the latest object attribute data handler(obj){ console.log("name = " + obj.name + "; age=" + obj.age); } } } }); </script>
watch usage scenario: it can monitor the changes of data in the view and respond; For example, in the drop-down box list, if the drop-down box option for is selected, some other data should be loaded according to the latest value.
13. Use of components
Objective: to understand the usage scenarios of components; Define the components counted by clicking, and use global registration and local registration methods
analysis:
Common or common page modules can be extracted into vue components and referenced in vue instances.
Summary:
The following experimental components can be found on the page:
<div id="app"> <!--Using components--> <counter></counter> <counter></counter> <counter></counter> </div> <script type="text/javascript"> //Define components const counter = { template:"<button @click='num++'>You clicked{{num}}second</button>", data(){ return {num:0} } }; //Global registration of components: components can be used in all vue instances //Parameter 1: component name, parameter 2: specific component //Vue.component("counter", counter); var app = new Vue({ el:"#app", components:{ counter: counter } }); </script>
Component usage scenario: a module (head, tail, news...) needs to be reused in the project Modules can be extracted into components, and components can be registered and referenced in other pages.
- Global registration: it can be referenced in any vue instance, such as the head navigation menu of a general website
- Local registration: components can be introduced into the pages where necessary, such as various activity modules in the home page of the mall website
14. Parent component communicates with child component
Objective: the meaning of communication between parent component and child component; Implement the parent component to update simple strings and objects to child components
Summary:
Significance of component communication: the exchange of data between parent and child components can update the component content in time.
- The parent component passes simple string updates to the child component
<div id="app"> <!--Use components--> <introduce :title="msg"></introduce> </div> <script type="text/javascript"> //Define components const introduce = { template:"<h2>{{title}}</h2>", //Defines the properties of the receive parent component props:["title"] }; //Global registration of components: components can be used in all vue instances //Parameter 1: component name, parameter 2: specific component Vue.component("introduce", introduce); var app = new Vue({ el:"#app", data:{ msg:"Parent component msg Attribute data content" } }); </script>
- The parent component passes array updates to the child component
<div id="app"> <!--Use components--> <my-list :items="lessons" ></my-list> </div> <script type="text/javascript"> //Define components const myList = { template:` <ul> <li v-for="item in items" :key="item.id">{{item.id}}--{{item.name}}</li> </ul> `, //Defines the properties of the receive parent component props:{ items:{ //The data type is Array if it is an Array and Object if it is an Object type:Array, //Default value default:[] } } }; var app = new Vue({ el:"#app", data:{ msg:"Parent component msg Attribute data content", :[ {"id":1, "name":"Java"}, {"id":2, "name":"Php"}, {"id":3, "name":"front end"} ] }, components:{ myList } }); </script>
15. Sub component communicates with parent component
Objective: click the corresponding button in the child component to change the attribute data in the parent component
Summary:
<div id="app"> <h2>num = {{num}}</h2> <!--Use components--> <counter @plus="numPlus" @reduce="numReduce" :snum="num"></counter> </div> <script type="text/javascript"> //Define components const counter = { template:` <div> <button @click='incrNum'>+</button> <button @click='decrNum'>-</button> </div> `, props:["snum"], methods:{ //Increasing incrNum(){ //Method called into parent component return this.$emit("plus"); }, decrNum(){ //Method called into parent component return this.$emit("reduce"); } } }; //Global registration of components: components can be used in all vue instances //Parameter 1: component name, parameter 2: specific component //Vue.component("counter", counter); var app = new Vue({ el:"#app", components:{ counter: counter }, data:{ num:0 }, methods:{ numPlus(){ this.num++; }, numReduce(){ this.num--; } } }); </script>
16. axios overview
Objective: to understand the use of axios and common methods
Summary:
axios: send asynchronous requests to get data. Common methods: get, post; When sending, you can specify parameters (address, request mode and request header information); Return data structure (data/status/statusText/headers/config)
17. Use of Axios method and get and post methods
Objective: use axios method to obtain data and traverse and display the data on the page; Switch to get/post method to load data
Summary:
You can use axios to obtain the corresponding server data; If the data is not from the same service, cross domain requests may occur; Cross domain needs to be configured on the responding server.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vuejs test</title> <script src="node_modules/vue/dist/vue.js"></script> <script src="js/axios.min.js"></script> </head> <body> <div id="app"> <ul> <li v-for="(user, index) in users" :key="index"> {{index}}--{{user.name}}--{{user.age}}--{{user.gender}} </li> </ul> </div> <script type="text/javascript"> var app = new Vue({ el:"#app", data:{ users:[] }, created(){ //Initialize load data axios.post("data.json").then(res=>{ console.log(res); //Assign the data to the data attribute users in the vue instance; //this cannot be used to represent the window in the axios callback function, not a vue instance app.users = res.data; }).catch(err=>alert(err)); axios.get("http://localhost/user/8").then(res=>{ console.log(res.data); }).catch(err=>alert(err)); /* axios.get("data.json").then(res=>{ console.log(res); //Assign the data to the data attribute users in the vue instance; //You cannot use this to represent the window in the axios callback function, not a vue instance app.users = res.data; }).catch(err=>alert(err)); */ /* axios({ url:"data.json", method:"get" }).then(res=>{ console.log(res); //Assign the data to the data attribute users in the vue instance; //You cannot use this to represent the window in the axios callback function, not a vue instance app.users = res.data; }).catch(err=>alert(err)); */ } }); </script> </body> </html>
Cross domain: if an asynchronous request is sent in the front-end js, the address of the request is different from the ip or port number of the current server. It is a cross domain request. You can configure it on the server side in the following ways:
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zrenBuT9-1624690357416)(assets/1561967287268.png)]
//Assign the data to the data attribute users in the vue instance;
//this cannot be used to represent the window in the axios callback function, not a vue instance
app.users = res.data;
}).catch(err=>alert(err));
/
/
axios({
url:"data.json",
method:"get"
}).then(res=>{
console.log(res);
//Assign the data to the data attribute users in the vue instance;
//this cannot be used to represent the window in the axios callback function, not a vue instance
app.users = res.data;
}).catch(err=>alert(err));
*/
}
});
Cross domain: if an asynchronous request is sent in the front-end js, the address of the request is different from the ip or port number of the current server. It is a cross domain request. You can configure it on the server side in the following ways:
[external chain picture transferring... (IMG zrenbut9-1624690357416)]