Vue
1, Introduction
-
Vue.js (read /vju ː/, Similar to view), it is a set of progressive framework for building "user interface". Vue only focuses on layers and adopts the design of bottom-up incremental development.
-
Vue is a view component that implements data binding and composition of responses through the simplest possible API.
-
Vue.JS is an excellent front-end JavaScript framework
2, Role
- With the complexity of the business scenario, the traditional mode (html+jquery) has been able to meet the requirements, and frameworks such as Angular/React/Vue have emerged
Enterprise needs, mainstream framework, ease of use, flexibility and efficiency
-
To the greatest extent, it liberates DOM operation
-
Single web item development
-
Traditional Web Station Development
3, Core features
① Decoupling views and data
② M-V-VM models focus on models and views
-
M: That is, Model, including data and some basic operations.
-
5: View, View, page render result
-
VM: view model, two-way operation between model and view
③ Bidirectional data binding
3.1 before MVVM
The developer obtains the required data Model from the back end, and then needs to operate the DOM to render the Model into the View. Later, when the user operates the View, we also need to obtain the data in the View through the DOM, and then synchronize it to the Model
3.2 after MVVM
What the VM in MVVM needs to do is to completely encapsulate the DOM operation. Developers will no longer be concerned about how the Model and View affect each other:
-As long as our Model changes, it will be displayed in the View.
-When users modify the View, the data in the Model will also change, freeing developers from tedious DOM operations and focusing on how to operate the Model
4, Use
4.1 download and installation
Vue is a front-end framework, which is also a js file. Download vue js text and introduce in page
vue.js download mode:
① It can lead to online vue JS (public CDN service)
② You can download Vue offline js
Development version: https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js
production version: https://cdn.jsdelivr.net/npm/vue@2
③ npm package resource manager, you can download vue js
Initialization: npm init -y
Install vue:npm install vue --save
Note: remember to restart the computer
be careful:
NPM is a module management tool provided by Node. You can easily download and install many front-end frameworks, including Jquery, AngularJS
VueJs. In order to facilitate later learning, we first install node and NPM tools
node.js download address: https://nodejs.org/en/download/ After installation, the Node should be equipped with NPM on the console
Input into npm -v to view
Note:
① The windows7 system is not supported in v12.16.2 or above.
② The default warehouse address of npm is in a foreign station, which is slow. It is recommended to set it to Taobao image. But switching the image is more troublesome
of Recommended image switching device: nrm
Installation command: NPM install nrm-g this-g represents global installation
View the warehouse list of npm: nrm ls
Specify image source: nrm use taobao
Test speed: nrm test npm
4.2 realization
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <h2>{{name}},Welcome!</h2> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script type="text/javascript"> //Create Vue instances var app=new Vue({ el:"#app",//el, that is, element. The page element to render data:{//data name:"Preferential employment" } }) </script> </body> </html>
Vue parameter details:
- In body, set the Vue management view
- Lead into vue js
- Instantiate Vue object new Vue();
- Set options for Vue instances, such as el, data
new Vue({option: value}); - stay The data in with data is generated by {}} in
5, Common instructions
Directives are special attribute s with a v-prefix. It is the syntax provided by the Vue framework, which extends the function of html tags. The value of the big part of the instruction is an expression of js. Replace DOM operation
5.1, v-text and v-html
Similar to innerText and innerHTML
① v-text: update content in label
② v-html: update content / tags in Tags
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <p v-text="t">What is this</p> <p v-html="h">Have a guess</p> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ t:"<i>ha-ha</i>", h:"<i>hey</i>" } }) </script> </body> </html>
5.2. v-if and v-show
Judge whether to render the element according to the boolean value of the expression
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <p v-if="b">What is this</p> <p v-show="b">Have a guess</p> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ b:false } }) </script> </body> </html>
- effect:
5.3,v-on
① Action: make the bind DOM event with v-on instruction, and execute some JavaScript code when the event is triggered.
② Syntax:
v-on: event name Modifier = "method name in methods";
Abbreviation of v-on: @ event name Modifier = "method name in methods";
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <button v-on:click="num++">Button 01</button><br />{{num}} <hr> <button @click="fn1()">Button 02</button> <button @click="fn2(num)">Button 03</button> <button @click="fn3">Button 04</button> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ num:0 }, methods:{ fn1:function(){ console.info("fn1 Adjusted..."+this.num); this.num++; }, fn2:function(n){ console.info("fn2 Adjusted...."+n); }, fn3:function(){ console.info("fn3 Adjusted...."); } } }) </script> </body> </html>
5.4,v-for
① Perform with: list rendering. When similar label structures are encountered, perform with v-for rendering
② Format:
[1] (item,index) in array or set
Parameter item: each element in the array
Parameter index: subscript of element in array
[2] (value, key, index) in object
Parameter index: the index of each pair of key values in the object starts from 0
Parameter key: key
Parameter value: value
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <!-- Traversal array --> <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> <!-- Traversal object --> <!-- Direct access --> <form action=""> <p><label>id: <input type="text" v-model="user.id"></label></p> <p><label>use account name:<input type="text" v-model="user.username"></label></p> <p><label>Age:<input type="text" v-model="user.age"></label></p> </form> <!-- ergodic --> <form action=""> <!-- <p v-for="value in user"> --> <p v-for="(value, key, index) in user"> <label>{{index}}-{{key}}: <input type="text" v-model="user[key]"> </label> </p> </form> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data: { userList: [ { id: 1, username: 'helen', age: 18 }, { id: 2, username: 'peter', age: 28 }, { id: 3, username: 'andy', age: 38 } ], user:{ id: 1, username: 'helen', age: 18 } } }) </script> </body> </html>
5.5,v-bind
① Action: you can bind any attribute on the label
② Format: v-bind: attribute = "value"
③ Short form:: attribute = "value"
④ Attribute value a partial input line replacement format:: attribute = "constant value + data in vue object data"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <font v-bind:color="v1">Employment</font> <font :color="v2">This is v-bind</font> <a :href="'http://'+u "> Baidu</a> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ v1:"red", v2:"yellow", u:"www.baidu.com" } }) </script> </body> </html>
5.6,v-model
① Action: binding of form elements
② Features: bidirectional data binding
(1) Data changes in the vue object can be updated to the bound
(2) You can change the data in the vue object through the bounds
(3) v-model ignores the initial values of the value, checked, and selected properties of all form elements. Vue is always implemented
Example as the data source. The initial value should be declared in the data option.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <form> use account name:<input type="text" v-model="user.name"><br> use account name:<input type="text" v-model="v"><br> password:<input type="password" v-model="user.password"><br> <input type="button" @click="fun1" value="obtain"> <input type="button" @click="fun2" value="modify"> </form> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ user:{name:"root",password:"1234"}, v:"hehe" }, methods:{ fun1:function(){ console.info(this.user.name); console.info(this.user.password); }, fun2:function(){ this.user.name="admin"; this.user.password="111"; } } }) </script> </body> </html>
5.7 calculation attributes
It is convenient to make the use js expression in the interpolation expression, and it is often used.
However, if the content of the expression is very simple, it will not be elegant enough, and it is not easy to maintain it later
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> {{message}} <p>{{birthday}}</p> Properties not calculated:<p>{{new Date(birthday).getFullYear() + '-'+ new Date(birthday).getMonth()+1+ '-' + new Date(birthday).getDate()}}</p> Calculation properties:<p>{{getBirth}}</p> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ message:"", birthday:1610669793429 }, created(){ this.message = "Created....."; console.info(this); }, computed:{ getBirth(){ const d = new Date(this.birthday); return d.getFullYear() + "-" + d.getMonth()+1 + "-" + d.getDate(); } } }) </script> </body> </html>
5.8,watch
watch allows us to monitor the changes of a values. Make corresponding response from .
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <input type="text" v-model="hello"> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ hello:"" }, watch:{ hello(newVal, oldVal){ console.log(newVal, oldVal); } } }) </script> </body> </html> View console
6, Life cycle
6.1 concept
Each Vue instance is created through a series of initialization processes: creating instances, loading templates, rendering templates, and so on. Vue sets the hook function (listening function) for each state in the life cycle. Each time a Vue instance is in a different "life cycle", the corresponding function will be triggered.
6.2 hook function
For example, created means after the Vue instance is created; We can define a created functions in Vue to represent the constructor of this period:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> {{message}} </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> const v = new Vue({ el:"#app", data:{ message:"" }, created(){ this.message = "Created....."; } }) </script> </body> </html>
7, Components
7.1. Define global components
We use Vue's component method to define global components.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <!--Make use defined components--> <con></con> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> // Parameter 1: component name parameter 2: component parameter Vue.component("con",{ template:"<button @click='count++'>Order me--{{count}}</button>", data(){ return { count:0 } } }) const v = new Vue({ el:"#app" }) </script> </body> </html>
characteristic:
-
In fact, a component is also a Vue instance, so it will also receive data, methods, life cycle functions, etc. during definition
-
The difference is that the component will not be bound to the element of page otherwise, it will be no undone, so there is no el attribute.
-
However, component rendering requires HTML template, so the template attribute is added. The value is the HTML template
-
After the global component is defined, any vue instance can directly use the component name in HTML to create a component.
-
The definition formula of data is special. It must be a function.
Note: define components to be declared before Vue objects
7.2 defining local components
Once you register globally, it means that even if you do not use this component in the future, it will still be loaded with the loading of Vue. Therefore, for some
For components that do not use use frequently, we will adopt use local registration.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue entry</title> </head> <body> <div id="app"> <conn></conn> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> // Local components const conn = { template:"<button @click='count1++'>Click me dry everything{{count1}}Times</button>", data(){ return { count1:0 } } } const v = new Vue({ el:"#app", components:{ conn:conn // } }) </script> </body> </html>
-components is the current vue object sub-component collection.
-
The key is the component name
-
Its value is the attribute of the component object
-
The effect is similar to the global registration just now. The difference is that this conn component can only make the use in the current Vue instance use
Note: define components to be declared before Vue objects
8, Vue's Ajax(axios)
In vue The essence of sending a network request in JS is ajax. We can make the plug-in easy to operate.
1,vue-resource: Vue.js plug-ins are no longer maintained. It is not recommended to use
2. axios: it is not a vue plug-in. It can be used anywhere. It is recommended
3. Examples of Http method rules for determining business operations (crud) through different types of Http requests (POST/DELETE/PUT/GET)
explain:
① POST Create add a resources without id
② GET Read get a resource
③ PUT Update updated a resource. Or add a resource with id (if the id does not exist)
④ DELETE Delete delete a resource
8.1 installation
Formula 1: install with npm
Command: npm install axios
Equation 2: make use cdn link axios
8.2 axios request
axios({ // Request type method: 'post', url: 'api', // Transfer parameters data: obj, // URLSearchParam() // Set request header information headers: { key: value }, responseType: 'json' }).then(response => { // Request succeeded let res = response.data; console.log(res); }).catch(error => { // Request failed, console.log(error); });
8.3 Get request
axios.get('/user?id=12345') .then(response => { console.log(response.data); }) .catch(error => { console.dir(error) });
8.4 Post request
axios.post('/user', "URLSearchParams") .then(response => { console.log(response.data); }) .catch(error => { console.dir(err) });
supplement
Aliases are provided for all requests held for convenience
- axios.request(confifig)
- axios.get(url[, confifig])
- axios.delete(url[, confifig])
- axios.head(url[, confifig])
- axios.post(url[, data[, confifig]])
- axios.put(url[, data[, confifig]])
- axios.patch(url[, data[, confifig]])
8.5 cross domain issues
- What is cross domain?
This means that the browser cannot execute scripts for other sites. It is caused by the same origin policy of the browser, and it is a security restriction imposed by the browser on javascript.
- What is homology strategy?
It refers to that the protocol, domain name and terminal must be the same, among which different domains will produce cross domains. When requesting data, the browser will report an exception in the console, prompting that access is denied.
- How do cross domain problems occur?
Develop some items that are separated from the front end and the back end. If the background code is started on one servers and the foreground code is started on one other computers during development with Servlet + Vue, problems will occur.
Compare for example:
Background address is http://192.168.70.77:8081
Front desk address is http://192.168.70.88:8080
At this time, the ip address is inconsistent with the terminal number, which does not conform to the source policy, resulting in cross domain problems.
Cross domain front end error presentation
resolvent
- Back end solution (custom filter)
Fang Formula 1: background solution(since defining filters) HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request = (HttpServletRequest) req; // Do not make with *, automatically adapt cross domain domain names to avoid invalidation when carrying cookies String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); // Adapt to all definition headers String headers = request.getHeader("Access-Control-Request-Headers"); response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", headers); // Allow cross domain request method method types response.setHeader("Access-Control-Allow-Methods", "*"); // Pre check command (OPTIONS) cache time, in seconds response.setHeader("Access-Control-Max-Age", "3600"); // Explicitly allow the client to send cookies without deleting fields response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(request, response);
- Front end solutions
① _ first npm Installed axios,Second, in main.js Middle lead import axios from 'axios' //Mount axios to the prototype of vue. Each component in vue can make use axios send requests Vue.prototype.$axios = axios //The important thing is this, vue prototype. Home ='/api'is a set value. It points to localhost by default. All modifications The pointing path is'/api',Configuration text parts index.js Defined cross domain paths Vue.prototype.HOME = '/api' ② Modify the above config>index.js Configuration text parts module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { //axios cross domain processing '/api': { //Here and url target:'http://192.168.2.80:8081/', changeOrigin:true, //Allow cross domain pathRewrite:{ '^/api': '' } } } } ③ Send in text pieces axios <template> <div id="app"> <button @click="fn">Click send axios</button> <router-view/> </div> </template> <script> export default { name: 'App', methods:{ fn:function(){ this.$axios.get(this.HOME+'/web02_war_exploded/servlet02') .then(response => { console.log(response.data); }) .catch(error => { console.dir(error) }); } } } </script>