Vue is a small and lightweight JavaScript library. It has a simple and easy-to-understand API that makes developers easier and more convenient when developing web applications. In fact, what has always made Vue proud of is its convenience, execution and flexibility.
The purpose of this tutorial is to use some examples to give you an overview of some basic concepts and features. In other tutorials, you will learn more useful features of Vue to build a scalable project with Vue.
Create a Vue instance using new Vue()
We can initialize an html page first, and then we need to introduce Vue's js file. There are many ways to introduce it. We can introduce Vue's cdn in script, or download Vue on the official website, or install a Vue dependency using npm. For convenience, this article is introduced using cdn.
<!DOCTYPE html> <html> <head> <title>Learn from scratchVue</title> </head> <body> <script src="/vue/1.0.16/"></script> </body> </html>
When you are developing, make sure you are using uncompressed versions, because uncompressed versions will provide useful detailed warnings and will save you a lot of time on your code writing.
We first write a div in the body, create a Vue instance, and then bind the instance and the div.
When you create a new Vue instance, use the Vue() constructor and point out your mount point in your instance. This mount point is the boundary of the Vue instance you want to divide. The mount point and the instance boundary correspond one by one. You can only handle transactions within the instance boundary at the mount point, but not transactions outside the instance boundary at your mount point.
The parameter for setting the mount point in the Vue instance is "el", and the value of el can be defined by the dom element.
<!DOCTYPE html> <html> <head> <title>Learn from scratchVue</title> </head> <body> <div >This is the instance boundary of the instance mount point</div> <script src="/vue/1.0.16/"></script> <script> // Create a new Vue instance and set the mount point var V = new Vue({ el : '#vueInstance' }); </script> </body> </html>
As you can see above, new Vue() creates a new instance and then specify a DOM element as the mount point of the instance. When defining the mount point, we use the id of the css selector to define it. The instantiated name can also be defined by itself for later call.
Using v-model for bidirectional data binding
We can use v-model to bind the input input box, so we can use dynamically to get the value of the data object. You can think of v-model as a specified property, just like the attribute of an html element. The two-way data binding here can be used on many form elements, such as input, textarea, and select.
Vue uses the v-model command to bind a data, and this data is the data we hope to be updated through user input operations.
For example, in our example below, we want to bind the data name on the input tag, and we need to implement the declaration in the data object in the Vue instance.
<div > Enter your name: <input type="text" v-model="name"> </div> <script src="/vue/1.0.16/"></script>//This line will be omitted afterwards<script> var V = new Vue({ el : '#vueInstance', data : { name : '_Appian' } }); </script>
No matter how many times the user enters, this name will be automatically updated. Also, if the value of name is changed, the values in other places where the name is mapped will also be modified. The reason for synchronous modification of this input box and mapping is to use the v-model instruction to allow the data to be bound through the underlying data stream and then modified directly. This is the concept of two-way binding of data.
To prove this concept, we can use $data to print out the mapping of data to see.
<div > Enter your name: <input type="text" v-model="name"> <p>{{ $data | json }}</p> //#1 <p>{{ name }}</p> //#2 </div> <script> var V = new Vue({ el : '#vueInstance', data : { name : '_Appian' } }); </script>
1 in:
$dataIt is a data object observed by Vue instances. Its essential type is an object, so it can be converted into json. Can be replaced with a new object. The instance proxies the properties of its data object.
{{}}, interpolate with two curly braces. The value inserted here is the value of $data that changes in real time.
| json, just a more intuitive way to display data. It can also be regarded as a filter, just like the effect of ().
In 2: {{ name }} means inserting data variables directly in the interpolation expression, two curly braces, and directly mapping the value of name.
Vue is so simple to perform two-way binding of data. It only requires a v-model instruction, without using js or jq to control data. I believe you can clarify the logic from the above examples.
Use v-on for event binding
Vue uses v-on instructions for event listening and event distribution. You can create a method to bind the listening event in Vue instance, and you can create a method to dispatch a click event.
In the following example, we will create a say method, which is bound to a button. The effect of clicking is to pop up a welcome box with the user name. In order to assign this method to the button, we need to use v-on:click to bind the event.
<div > Enter your name: <input type="text" v-model="name"> <button v-on:click="say">Welcome to click</button> //#1 <button @click="say">Welcome to click</button> //#2 </div> <script> var V = new Vue({ el : '#vueInstance', data : { name : '_Appian' }, methods : { say : function(){ alert('welcome' + ); } } }); </script>
Of course, not only can you bind click click events, but you can also bind other mouse events, keyboard input events and other js event types. For example, v-on:mouseover, v-on:keydown, v-on:submit, v-on:keypress, v-on:keyup.13, etc., or some other custom events.
During the development process, you may frequently use event binding. It is a bit troublesome to write v-on, so in the above example, there are two ways to write, #2 is the abbreviation of #1. Using @ instead of v-on, I won't say much here.
Use v-if or v-show to make conditional judgments
If we want the user to see the welcome pop-up window after logging in, and if we are not logged in, we will give it a login interface. Vue will provide us with v-if and v-show instructions to control the display content under different login states.
Using the previous example, we can use the value of loginStatus to control whether to log in. If it is true, the input box and button will be displayed so that it can see the welcome pop-up window. However, if it is false (that is, it is not logged in), you can only see the input box and the submission button for entering the account number, password (there is no authentication for the time being, only the login status will be changed).
<div > //The section displayed when loginStatus is true <section v-if="loginStatus"> Enter your name: <input type="text" v-model="name"> <button v-on:click="say">Welcome to click</button> <button @click="switchLoginStatus">Log out</button> </section> //The section displayed when loginStatus is false <section v-if="!loginStatus"> Log in to the user: <input type="text"> Login password: <input type="password"> <button @click="switchLoginStatus">Log in</button> </section> </div> <script> var V = new Vue({ el : '#vueInstance', data : { name : '_Appian', loginStatus : false }, methods : { say : function(){ alert('welcome' + ); }, switchLoginStatus : function(){ = !; } } }); </script>
The execution of this is instance V. This pointing is a question that needs to be understood by oneself, so I won’t talk about it here. In the above example, as long as V-if is replaced with v-show, the same effect can be obtained. Both v-if and v-show support v-else, but the previous sibling element of the tag that binds the v-else command must have v-if or v-show.
In the above example, just clicking the "Login" or "Login Out" button will trigger the switchLoginStatus method. As long as this method is triggered, the status of loginStatus will change (switching in true and false), thereby changing the change of the judgment condition result of v-if in html. Based on the current Boolean status of loginStatus, the displayed section is a section in different states.
What is the difference between v-show and v-if?
When switching v-if blocks, Vue has a local compilation/uninstallation process, because templates in v-if may also include data binding or subcomponents. v-if is a real conditional rendering because it ensures that the conditional blocks properly destroy and rebuild event listeners and subcomponents within the conditional block during the switch.
v-if is also lazy: if the condition is false at the initial rendering, nothing is done - local compilation starts when the condition becomes true for the first time (compilation will be cached).
v-show is much simpler in comparison – elements are always compiled and preserved, just simply switched based on CSS.
Generally speaking, v-if has higher switching consumption and v-show has higher initial render consumption. Therefore, it is better to switch frequently if v-show is needed, and it is better to change v-if if the conditions are unlikely to change at runtime.
This difference may not be important to your current development, but you still need to pay attention and pay attention, because when your project development becomes larger, this will become important.
Use v-for to output list
If you are a businessman who runs an e-commerce platform, you must have many pages that need to render the output of the product list. The v-for directive allows looping our array object, pronounced as "looping every element in arrayObj" in the way of "element in arrayObj".
In the following example, we will use the v-for instruction to loop out a product list. Each product will be in a li, where the name, price and product type of the product are output.
<div > <ul> <li v-for="el in products"> {{ }} - ¥ {{ el. price }} - {{ el. category }} </li> </ul> </div> <script> var V = new Vue({ el : '#vueInstance', data : { products : [ {name: 'microphone', price: 25, category: 'electronics'}, {name: 'laptop case', price: 15, category: 'accessories'}, {name: 'screen cleaner', price: 17, category: 'accessories'}, {name: 'laptop charger', price: 70, category: 'electronics'}, {name: 'mouse', price: 40, category: 'electronics'}, {name: 'earphones', price: 20, category: 'electronics'}, {name: 'monitor', price: 120, category: 'electronics'} ] } }); </script>
Of course, the array object in data can be defined without the above definition. We can import it from the database or use ajax request to obtain it. This is just for demonstration of v-for.
Sometimes we may need to get the corresponding subscript of the product in the array object. We can get it with $index.
//#1 <li v-for="el in products"> {{ $index }} - {{ }} - ¥ {{ el. price }} - {{ el. category }} </li> //#2 <li v-for="(index,el) in products"> {{ index }} - {{ }} - ¥ {{ el. price }} - {{ el. category }} </li>
Computed properties
In the application scenario of calculating attributes, it is generally used when there is a variable value that needs to be calculated by other variables.
For example, if a user enters a number x in the input box, it will automatically return to the user the square x² of the number. You need to bind the input box data, and then when the data is modified, it will immediately calculate its square.
<div > Enter a number: <input type="text" v-model="value"> <p>Calculation results:{{ square }}</p> </div> <script> var V = new Vue({ el : '#vueInstance', data : { value : 1 }, computed : { square : function(){ return * ; } } }); </script>
Calculate attribute definition values by defining a series of functions, just like when we defined methods objects before. For example, the square method is used to calculate the variable "square", and the return value of its method is the product of two.
Next, we can use computed to make a more complicated example. The system will randomly take a number within 1~10. The user can randomly enter a number within 1~10 in the input box. If the user's input happens to match the system's random number, the game will succeed, otherwise it will fail.
<div > enter1~10Numbers within: <input type="text" v-model="value"> <p>Calculation results:{{ resultMsg }}</p> </div> <script> var V = new Vue({ el : '#vueInstance', data : { value : null, randNum : 5//The first random number is 5 }, methods : { getRandNum: function(min, max){ return (() * (max - min + 1)) + min; } }, computed : { resultMsg : function(){ if ( == ) { = (1, 10); return 'You guessed it right!'; } else { = (1, 10); return 'I guessed wrong, come again!'; } } } }); </script>
postscript
So far, you have been able to master the basic use of Vue, one of the simplest and most beautiful frameworks in the world. Its construction has its own complete design ideas and is becoming more and more popular. This framework is small and light enough to bring you a smoother user experience in your development and effectively improve development efficiency.I have given a series of examples above, have you mastered them all?
Use new Vue() to create a new Vue instance and set the mount point
Use v-model directive to bind form controls in two-way
Understand the usage of $data , {{}} , $index when outputting data
Use v-on for event binding, usage of methods
Combined with v-on, use v-if or v-show to make conditional judgments and understand the differences
Use v-for to loop out the list
Basic application of computing attribute Computed
Now you have basically mastered the basics of Vue. The next thing you have to do is to check out some of the latest news about Vue, or continue to learn about Vue's journey with me.
github address:/AppianZ/Close2Vue
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.