Vue quick start (I) (for emergency use)
1, Downloading and importing Vue
To use vue, first of all, we must refer to the "dependency" of vue. There are two methods:
Method 1: go to the official website to download the vue.js file
Click here to download the vue.js file (since the get request is sent here and cannot be downloaded directly, you have to copy the content under the website and put it into a blank vue.js file for use.)
Method 2: use the online vue.js
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
2, First Vue program
Learning programs, first of all, hello,world. Directly paste the source code: (the analysis of the source code is under the source code)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello,World</title> <!--Import Vue--> <script type="text/javascript" src="../js/vue.js" charset="UTF-8"></script> </head> <body> <div id="app"> {{message}} </div> <script type="text/javascript"> let app = new Vue({ el:'#app', data:{ message: "Hello,world" } }); </script> </body> </html>
Resolution:
<script type="text/javascript" src="../js/vue.js" charset="UTF-8"></script>
This sentence is introduced into our Vue. Needless to say, we should know it.
<div id="app"> {{message}} </div>
This paragraph defines the id of our div as app, and then uses two curly braces {}} to refer to the attribute of the data we define.
<script type="text/javascript"> let app = new Vue({ el:'#app', data:{ message: "Hello,world" } }); </script>
This paragraph is the most critical. In Ajax, the step of new Vue is actually equivalent to $, and then el is actually our element, # means to get the id value, writing the string directly means to get the label, and. Class name means to get the class. Then data is the variable assigned in it. We can get it through {variable name}}.
Note: vue should be used at the bottom of the body. Otherwise, the message may not be rendered normally because the id cannot be obtained.
We have successfully created the first Vue application! It looks very similar to rendering a string template, but Vue has done a lot of work behind it. Now the data and DOM have been associated, and everything is responsive. How do we confirm? Open your browser's JavaScript console (which opens on this page) , and modify the value of app.message, and you will see that the above example is updated accordingly.
Note that we no longer interact directly with HTML. A Vue application will mount it to a DOM element (for this example, #app) and then fully control it. That HTML is our entry, but the rest will occur inside the newly created Vue instance.
3, Conditions and cycles
The v-if attribute indicates the condition:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Conditions and cycles</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="demo"> <p v-if="seen">Now you can see me!</p> </div> <script type="text/javascript"> let demo = new Vue({ el:"#demo", data:{ seen: true } }); </script> </body> </html>
Display:
We can change his see to false in the console and hide it.
The loop statement is also very simple. Use the v-for tag to traverse, indicating which variable to traverse, and the variable of each attribute to be traversed.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Circular statement</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <ul id="List"> <li v-for="item in studentList"> Student No.:{{item.id}}, full name:{{item.name}}, Age:{{item.age}} </li> </ul> <script type="text/javascript"> let demo = new Vue({ el:"#List", data:{ studentList:[ {id:'1001',name:'Zhang San',age:18}, {id:'1002',name:'Zhang San',age:18}, {id:'1003',name:'Zhang San',age:18}, {id:'1004',name:'Zhang San',age:18}, {id:'1005',name:'Zhang San',age:18}, ] } }); </script> </body> </html>
result:
4, Process user input (event listener)
In order to allow users to interact with your application, we can add an event listener with the v-on instruction and call the methods defined in the Vue instance through it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>monitor</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="onDemo"> <p>{{message}}</p> <button v-on:click="updateMsg">Click to modify the paragraph content</button> </div> <script type="text/javascript"> let demo = new Vue({ el:"#onDemo", data:{ count:0, message:'I'm a popular paragraph' }, methods:{ updateMsg: function () { if(++this.count %2 == 0){ this.message = 'Anyway, I'm a favorite paragraph.' }else { this.message = 'I told you that I will always be loved by everyone.' } } } }) </script> </body> </html>
Display:
The odd number of clicks on the button displays:
Click the button even times to display:
Vue also provides v-model instructions, which can easily realize the two-way binding between form input and application state.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Event binding</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="demo"> <p>{{message}}</p> <input v-model="message"> </div> <script type="text/javascript"> let demo = new Vue({ el:"#demo", data:{ message:'Hello' } }) </script> </body> </html>
Run: (p can read the contents of input and display them in real time)
5, Vue instance
5.1 $watch (when a variable is modified, called)
By calling the $watch method of the object returned by new Vue(), every time a variable changes
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>monitor</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="onDemo"> <p>{{message}}</p> <button v-on:click="updateMsg">Click to modify the paragraph content</button> </div> <script type="text/javascript"> let demo = new Vue({ el:"#onDemo", data:{ count:0, message:'I'm a popular paragraph' }, methods:{ updateMsg: function () { if(++this.count %2 == 0){ this.message = 'Anyway, I'm a favorite paragraph.' }else { this.message = 'I told you that I will always be loved by everyone.' } } } }); //Listen to the count variable of demo demo.$watch('count', function (newVal, oldVal) { console.log("The oldVal of count is "+oldVal); console.log("The newVal of count is "+newVal); }); //Listen to the message variable of the demo demo.$watch('message',function (newVal, oldVal) { console.log("The oldVal of message is "+oldVal); console.log("The newVal of message is "+newVal); }); </script> </body> </html>
result:
After clicking the button twice:
5.2 life cycle
Just look at the picture directly. It doesn't matter if you don't understand what you haven't learned. Just come back and have a look when you've learned almost.
Let's talk about it: the main thing here is to know when these methods (also known as hooks) will be called, such as
hook | Call time |
---|---|
beforeCreate | Before Vue objects are created |
created | After the Vue object is created |
beforeMount | Before el rendering to html |
mounted | After el rendering to html |
beforeUpdate | Before the data changes |
updateed | After data changes |
beforeDestroy | Before removing the watcher, sub assembly and event listener |
destroyed | After removing the watcher, sub assembly and event listener |
The usage is also relatively simple. Here is an example:
let demo = new Vue({ el:"#onDemo", data:{ count:0, message:'I'm a popular paragraph' }, created: function(){ console.log("The count is "+this.count); console.log("The message is "+this.message); }, methods:{ updateMsg: function () { if(++this.count %2 == 0){ this.message = 'Anyway, I'm a favorite paragraph.' }else { this.message = 'I told you that I will always be loved by everyone.' } } }, });
6, Template syntax
6.1 text
The most common form of data binding is text interpolation using "Mustache" syntax (double braces):
<span id="demo"> {{ msg }}\ </span>
The Mustache tag will be replaced with the value of the msg attribute on the corresponding data object. Whenever the msg attribute on the bound data object changes, the content of the interpolation will be updated.
If we don't want this value to change, we can add the v-once attribute to the corresponding tag. (Note: this will affect other data bindings on the node)
< span id = "demo" v-once > this will not change: {MSG}}</span>
6.2 original HTML
Double curly braces will interpret the data as plain text instead of HTML code. In order to output real HTML, you need to use the v-html instruction:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>original HTML</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <p id="demo">Using mustaches: {{ rawHtml }}</p> <!-- <p id="demo">Using v-html directive: <span v-html="rawHtml"></span></p>--> <script> demo = new Vue({ el:"#demo", data:{ rawHtml: '<span style="color:red">This should be red.</span>' } }) </script> </body> </html>
result:
If so:
<!-- <p id="demo">Using mustaches: {{ rawHtml }}</p>--> <p id="demo">Using v-html directive: <span v-html="rawHtml"></span></p>
result:
Note: arbitrary HTML rendered dynamically on our own site can be very dangerous because it can easily lead to XSS attacks. Please use HTML interpolation only for trusted content and never for user provided content.
6.3 Attribute
Mustache syntax cannot be used on HTML attribute s. In this case, you should use the v-bind instruction:
<div v-bind:id="dynamicId"></div>
For Boolean attribute s (their existence means that the value is true), v-bind works slightly differently. In this example:
<button v-bind:disabled="isButtonDisabled">Button</button>
If the value of isButtonDisabled is null, undefined, or false, the disabled parameter will not even be included in the rendered < button > element.
6.4 using JavaScript expressions
So far, in our template, we have only bound simple attribute values. But in fact, Vue.js provides full JavaScript expression support for all data binding. For example, we can write:
{{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') }} <div v-bind:id="'list-' + id"></div>
These expressions will be parsed as JavaScript under the data scope of the Vue instance. One limitation is that each binding can only contain a single expression, so the following examples will not take effect.
<!-- This is a statement, not an expression --> {{ let a = 1 }} <!-- Flow control will not take effect, please use ternary expression --> {{ if (ok) { return message } }}
6.5 instructions
In fact, we talked a little before, but I didn't call them instructions, but more commonly, I called them attributes. What is the instruction? It's actually an attribute that starts with V -. (for example, we have already touched v-if, v-for, v-bind, v-html, v-once, v-on, v-model)
Some instructions can even receive a parameter, represented by a colon after the instruction name. For example, the v-bind instruction can be used to responsively update HTML attributes:
<a v-bind:href="url">...</a>
Usage:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jump to Baidu</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <a id="addr" v-bind:href="url">Jump to Baidu</a> <script> new Vue({ el:"#addr", data:{ url: "http://www.baidu.com" } }) </script> </body> </html>
result:
Click to jump to Baidu page.
There is also a v-on event listener for binding tags. (take a look at the previous example and recall that when you click the button, his updateMsg method is called.)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>monitor</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="onDemo"> <p>{{message}}</p> <button v-on:click="updateMsg">Click to modify the paragraph content</button> </div> <script type="text/javascript"> let demo = new Vue({ el:"#onDemo", data:{ count:0, message:'I'm a popular paragraph' }, created: function(){ console.log("The count is "+this.count); console.log("The message is "+this.message); }, methods:{ updateMsg: function () { if(++this.count %2 == 0){ this.message = 'Anyway, I'm a favorite paragraph.' }else { this.message = 'I told you that I will always be loved by everyone.' } } }, }); //Listen to the count variable of demo demo.$watch('count', function (newVal, oldVal) { console.log("The oldVal of count is "+oldVal); console.log("The newVal of count is "+newVal); }); //Listen to the message variable of the demo demo.$watch('message',function (newVal, oldVal) { console.log("The oldVal of message is "+oldVal); console.log("The newVal of message is "+newVal); }); </script> </body> </html>
Starting with Vue version 2.6.0, we can also use JavaScript expressions enclosed in square brackets as parameters of an instruction:
<a v-bind:[attributeName]="url"> ... </a>
Here, if the attributeName value in our data is "href", then this binding will be equivalent to v-bind:href. Then the url is also the attribute value in data.
Of course, this dynamic parameter expression is also constrained. Some characters, such as spaces and quotation marks, are invalid in HTML attributes. For example, < a v-bind: ['foo '+ bar] = "value" >... < / a >, this will trigger a compilation warning. The natural solution is to use an expression without spaces or quotation marks, or replace this complex expression with a calculated attribute.
Note: when using a template in DOM (writing a template directly in an HTML file), you also need to avoid using uppercase characters to name the key name, because the browser will force all attribute names to lowercase:
For example, < a v-bind: [someattr] = "value" >... < / a >, will be equivalent to < a v-bind: [someattr] = "value" >... < / a >.
6.6 abbreviations
As a visual cue, the v-prefix is used to identify Vue specific attribute s in the template. When you use Vue.js to add dynamic behavior to existing tags, the v-prefix is very helpful. However, for some frequently used instructions, it will feel cumbersome to use. Therefore, Vue also provides specific abbreviations for the two most commonly used instructions, v-bind and v-on:
The of v-bind is as follows:
<!-- Complete grammar --> <a v-bind:href="url">...</a> <!-- abbreviation --> <a :href="url">...</a> <!-- Abbreviations for dynamic parameters (2.6.0+) --> <a :[key]="url"> ... </a>
The abbreviations of v-on are as follows:
<!-- Complete grammar --> <a v-on:click="doSomething">...</a> <!-- abbreviation --> <a @click="doSomething">...</a> <!-- Abbreviations for dynamic parameters (2.6.0+) --> <a @[event]="doSomething"> ... </a>
7, Compute properties and listeners
The expressions in the template are very convenient, but they are designed for simple operations. Putting too much logic in the template will make the template too heavy and difficult to maintain. For example:
<div id="example"> {{ message.split('').reverse().join('') }} </div>
In this place, templates are no longer simple declarative logic. You have to look for a while to realize that here is the flipped string of the variable message you want to display. When you want to include this flipped string in multiple places in the template, it will be more difficult to deal with.
Therefore, for any complex logic, we should use computational attributes to extract them into a "method".
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Calculation properties</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> <p>random number:{{randomMessage}}</p> </div> <script type="text/javascript"> var vm = new Vue({ el: '#example', data: { message: 'Hello' }, //Below computed is a series of methods for calculating attributes! computed: { // getter of calculated property reversedMessage: function () { // `this ` points to the vm instance return this.message.split('').reverse().join('') }, randomMessage: function () { return Math.floor(Math.random()*100); } } }) </script> </body> </html>
result:
Here, some people may say, isn't it the same if I write it as a method and call it again? We can write like this. It's also right. What's the difference? The answer is that computed properties are cached based on their responsive dependencies. They are re evaluated only when the relevant responsive dependencies change. This means that as long as the message has not changed, multiple accesses to the reversedMessage calculation property will immediately return the previous calculation result without executing the function again. If we write it under methods and call it, it will re evaluate and return every time.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Calculation properties</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> <p>Computed reversed message: "{{ reversedMessageFun() }}"</p> <p>random number:{{randomMessage}}</p> </div> <script type="text/javascript"> var vm = new Vue({ el: '#example', data: { message: 'Hello' }, //Below computed is a series of methods for calculating attributes! computed: { // getter of calculated property reversedMessage: function () { // `this ` points to the vm instance return this.message.split('').reverse().join('') }, randomMessage: function () { return Math.floor(Math.random()*100); } }, methods:{ reversedMessageFun : function(){ return this.message.split('').reverse().join('') } } }) </script> </body> </html>
In addition, when we have some data that needs to change with other data changes, we can easily abuse Watch - especially if you have used AngularJS before. However, it is usually better to use calculated properties rather than an imperative watch callback.
Let's look at the way watch is written:
<div id="demo">{{ fullName }}</div> <script type="text/javascript"> let vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } }) </script>
However, if we use the calculation attribute, it is:
<div id="demo">{{ fullName }}</div> <script type="text/javascript"> let vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar' }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } }) </script>
We have been using the getter to calculate properties above, but occasionally we may need to use its set method
// ... computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ...
Now, when vm.fullName = 'John Doe' is run again, the setter will be called, and vm.firstName and vm.lastName will be updated accordingly.