VUE Foundation
1. What is vue?
At present, the front-end has three very popular frameworks, namely angularjs, reactjs and vuejs. Among the three, vuejs has the highest popularity at present, and the one who developed vuejs is you Yuxi, a Chinese.
Association with other frameworks
- Learn from angular's template and data binding technology
- Learn from react's componentization and virtual DOM Technology
Basic concepts
vue.js official document says Vue is a progressive JavaScript framework. Let's explain the concepts one by one.
Progressive
vue family bucket actually contains many vue extensions, such as the following.
- Vue cli: Vue scaffold
- Vue resource (Axios): Ajax request
- Vue Router: route
- vuex: status management
- Vue lazload: image lazy load
- Vue scroller: page sliding related
- Mint UI: vue based component library (mobile terminal)
- Element UI: vue based component library (PC side)
You can use vue step by step and in stages, without having to use everything at the beginning. This is progressive.
Javascript: Needless to say, vue itself is based on JavaScript.
frame
We often used some plug-ins before, such as jQuery and swiper. Let's talk about the difference between plug-ins and frameworks.
Plug in: it provides a small function, which is less invasive to the project, and can be easily switched to other libraries to meet the requirements.
Framework: it is a complete solution, which can be understood as a collection of plug-ins; It is very invasive to the project. If the framework needs to be replaced, the whole project needs to be reconstructed.
Framework can improve our development efficiency. For enterprises, time is money and efficiency is everything. The same work, vue can save a lot of time, so we can go out to date girlfriends and play games. Isn't it cool? If you don't work hard, how can your boss change a new car and a new house?
2. vue core concept
Data driven
Through data-driven interface update, there is no need to operate DOM to update the interface
Follow MVVM mode (we'll talk about what MVVM mode is later). Using Vue, we only need to care about how to obtain data, how to process data, and how to write business logic code,
We just need to hand over the processed data to Vue, and Vue will automatically render the data to the template (on the interface)
Component development
Like Lego blocks, we first create the blocks we need, and then splice the graphics we need through the blocks. Similarly, we can split the web page into independent components to write, and then splice the encapsulated components into a complete web page.
3. Basic use of vue
3.1 introduction method
vue can be used in two ways:
The first method: traditional introduction method, Download Vue JS file and introduce it in the page.
The second is to use Vue cli to install and import.
At this stage, we can use the first method, and we will talk about the use of the second method later.
3.2 use steps
-
Download Vue framework
Official address: https://cn.vuejs.org/
But vue's official download address is on GitHub. For domestic students, it is often inaccessible, so we can download it through the rookie tutorial.
https://www.runoob.com/vue2/vue-install.html
Click download Vue JS, in the newly opened page, right-click and select Save as, and select the download address to successfully download.
-
Import Vue framework
<!--Import Vue.js --> <script src="js/vue.js"></script>
-
Create Vue instance object
You can create an instance of Vue through the constructor Vue.
// Create an instance object of Vue let vue = new Vue();
-
Specifies the area controlled by the Vue instance object
<div id="app"> <p>{{ name }}</p> </div>
Vue's constructor needs to pass in a parameter when calling. This parameter is an object in which almost all our Vue related code is written.
Among them, el is an essential option. The value of el can be an element node or a css selector. The css selector is the one we use most.
let vue = new Vue({ // Tell the instance object of Vue which area of the interface needs to be controlled in the future el: '#App '/ / or document getElementById("app") });
-
Specifies the data for the Vue instance object control area
let vue = new Vue({ el: '#app', // Tell Vue's instance object what the data of the controlled area is data: { name: "Li Nanjiang" } });
4. Interpolation and expression
Double curly braces {}} is the most basic text interpolation method. It will automatically take out the data in the data attribute of our vue instance and display it in our page.
<p>Hello {{msg}}</p>
let vm = new Vue({ el: '#app', data: { msg: "vue" } });
5. Data binding
5.1 MVVM design pattern
As we said earlier, Vue follows the MVVM pattern. What is the MVVM pattern?
In fact, MVVM is short for model view view model.
M: model refers to the data transferred from the back end.
V: view refers to the page you see.
VM: View Model is the core of mvvm mode. It is the bridge between view and model.
It has two directions:
First, convert the [model] into [view], that is, convert the data transmitted from the back end into the page you see.
The second is to convert the view into the model, that is, the page you see into the back-end data.
These two directions are realized, which we call two-way binding of data.
in other words:
As long as the data value in data is changed, the interface will automatically update the data = = > template page
Change the input data of the page, and the data in data can also change the template page automatically = = > data
5.2 one way data binding
<!--Here it is MVVM Medium View--> <div id="app"> <p>{{ msg }}</p> </div>
// Here is the View Model in MVVM let vue = new Vue({ el: '#app', // Here is the Model in MVVM data: { msg: "vue" } });
By modifying the value of msg in any way, the content in the HTML page will be replaced in real time.
For example, we can directly use the following code in the console, and the content of the p tag will change accordingly.
vue.msg = "zhang"
[tip]: the data written in data will be automatically attached to the instance of vue, so we can directly use the instance object to call.
5.3 bidirectional data binding
On form elements such as input and textarea, you can create two-way data binding with v-model instruction
<div id="app"> <input type="text" v-model="msg"> <p>hello,{{ msg }}</p> </div> <script> // Here is the View Model in MVVM let vue = new Vue({ el: '#app', // Here is the Model in MVVM data: { msg: "vue" } }); </script>
Bury a pit here. What is the two-way binding principle of vue? Let's not talk about it first. After we are familiar with vue in two days, we will come back to this. This is also a point that may be asked in the interview.
6. Instruction
Specifying is one of the most commonly used functions in Vue templates. It is a custom label attribute starting with v -.
6.1 v-text
To display the data in data on the page, you can use v-text in addition to double braces {}} for interpolation
<span v-text="msg"></span> <!-- Same as below --> <span>{{ message }}</span>
new Vue({ el:"#app", data : { message : "it's a nice day today" } })
Difference between v-text and interpolation expression {}}
v-text will overwrite the original content of the element. The interpolation expression {}} will only replace its own placeholder, not the whole element content.
var app = new Vue({ el: '#app', data: { text:'hello' } })
<span v-text='text'>vue</span> <!-- vue Will be overwritten and the result is hello --> <span>{{text}},vue</span><!--The result is hello,vue -->
6.2 v-html
In the above case, if the value in msg is an HTML tag string, we will not parse the HTML code in msg when the page is loaded, for example:
<div id="app"> {{ msg }} </div> <script> let vue = new Vue({ el: '#app', data: { msg: "<h1>hello,vue</h1>" } }); </script>
In the page, it will be displayed like this
If we want the page to parse the HTML code in the data, we can use v-html to point to.
<div id="app" v-html="msg"> </div> <script> let vue = new Vue({ el: '#app', data: { msg: "<h1>hello,vue</h1>" } }); </script>
6.3 v-bind
Function: dynamically update attributes on HTML elements. For example: ID, class, href, src, etc
Format: v-bind: attribute name = "bound data"
<img src="url"><!-- Wrong writing --> <img v-bind:src="url">
var app = new Vue({ el:"#app", data:{ url:"xxx.png" } })
Grammar sugar
Syntax sugar refers to using some method to achieve the same effect without affecting the function, so as to facilitate the development of the program. Like the sugar beans we ate when we were young, they are essentially medicine, but they taste sweet and like sugar.
The format of v-bind uses syntax. The sugar is written as follows:
: property name = "bound data"
Modify the code in the above HTML code, and the effect is the same.
<img v-bind:src="url">
6.4 v-on
Function: event binding.
Format: v-on: event type = "function name"
It also has the grammatical sugar writing method: omit v-on: use the @ symbol instead
@Event type = "function name"
<button v-on:click="myFn()">I'm the button</button> <!-- The two are the same --> <button @click="myFn()">I'm the button</button>
However, the functions we define directly in js cannot be. We need to write the event function in the method attribute in the vue instance.
let vue = new Vue({ el: '#app', //The function needs to be written here methods: { myFn(){ alert('You clicked the button') } } });
parameter
You can pass parameters to the bound callback function
Access data
If you need to use the data in data in the bound function, you must add this
Event object
@The method name called by click can be followed by parentheses or not. If the method has parameters and we do not write parentheses, the native event object event will be passed in by default.
<button @click="myFn">I'm the button</button>
let vue = new Vue({ el: '#app', //The function needs to be written here methods: { myFn(param){ console.log(param) } } });
You can see what param prints out
This is the object of the event!
If the method has parameters, we also need to handle the event object, such as preventing the default behavior of a tag. So what should I do?
vue provides a special variable $event to access native DOM events. For example:
<a href="http://www.baidu. Com "@ Click =" myfn ('No jump ', $event) "> I'm the button</a>
let vue = new Vue({ el: '#app', methods: { myFn(msg,event){ event.preventDefault(); console.log(msg) } } });
Modifier
In the above case, we can also use modifiers. Add a dot '.' after the @ bound event, Followed by a suffix to use the modifier.
Common modifiers are as follows:
- Stop: stop bubbling
- Prevent: prevent browser default behavior
- Once: only triggered once.
<div class="a" @click="myFn1"> <div class="b" @click.stop="myFn2"> <div class="c" @click="myFn3"></div> </div> </div>
let vue = new Vue({ el: '#app', methods: { myFn1(){ console.log("grandpa"); }, myFn2(){ console.log("dad"); }, myFn3(){ console.log("Son"); } } });
When listening for keyboard events on form elements, you can also use key modifiers, such as pressing a specific key to call the method:
<!-- Only in keycode Is 13, which is called only when the Enter key is pressed myFn function --> <input @keyup.13="myFn">
6.5 v-if
Conditional rendering: if the value of v-if is true, the element will be rendered; if it is false, the element will not be rendered (dom does not exist)
v-if can obtain data from the model or directly assign an expression
<p v-if="show">display</p> <p v-if="age >= 18">Welcome to Internet cafe</p>
let vue = new Vue({ el: '#app', data: { show: true, age: 17, } });
v-else instruction
V-else can be used with v-if instruction. When v-if does not meet the conditions, v-else will be executed and the contents of v-else will be displayed
<p v-if="age >= 18">Welcome to Internet cafe</p> <p v-else>Come in through the back door</p>
let vue = new Vue({ el: '#app', data: { age: 17, } });
v-else-if instruction
V-else-if can be used in conjunction with v-if instructions. When v-if does not meet the conditions, follow-up v-else-if will be executed in turn, and the one that meets the conditions will be displayed
<p v-if="score >= 80">excellent</p> <p v-else-if="score >= 60">good</p> <p v-else>difference</p>
let vue = new Vue({ el: '#app', data: { score: 70, } });
[note]
- There can be no other content between v-if, v-else and v-else-if
- V-else and v-else-if cannot appear alone
6.6 v-show
Conditional rendering instruction
If the expression is true, the element is displayed; if false, the element is hidden (dom exists)
<p v-show="show">display</p> <p v-show="age >= 18">Welcome to Internet cafe</p>
let vue = new Vue({ el: '#app', data: { show: true, age: 17, } });
v-if and v-show application scenarios
When the value of v-if is false, the element will not be created, so if you need to switch the display and hiding of the element, the element will be created and deleted every time
When the value of v-show is false, the element will be created and the display will be set to none. If it is necessary to switch the display and hiding of elements,
It will not be created and deleted repeatedly, but the value of display will be modified
Therefore: if you need to frequently switch the display and hiding of elements in enterprise development, v-show is recommended, otherwise v-if is used
6.7 v-for
List rendering instruction
When we need to traverse an array or enumerate the properties of an object, we can use the v-for instruction. Some are similar to the for in loop.
<div id="app"> <ul> <li v-for="user in users">{{user.name}}</li> </ul> </div>
let vue = new Vue({ el: '#app', data: { users:[ {name:"Zhang San"}, {name:"Li Si"}, {name:"Wang Wu"} ] } });
v-for also supports an optional parameter as the index of the current item. For example, modify the HTML code above:
<div id="app"> <ul> <li v-for="(user,index) in users">{{index}}-{{user.name}}</li> </ul> </div>
In addition to arrays, v-for can also traverse, strings, numbers, and objects.
<div id="app"> <ul> <li v-for="value in person">{{value}}</li> </ul> </div>
let vue = new Vue({ el: '#app', data: { person:{ name:"Zhang San", age:"20", habby:"Look at beauty" } } });
When traversing object properties, there are two optional parameters, representing key name and index respectively.
<li v-for="(value,key,index) in person">{{index}}----{{key}}-----{{value}}</li>
Traversal integer:
<span v-for="n in 10">{{n}}</span>
Array update
The core of Vue is the bidirectional binding of data and view. When we modify the array, Vue will detect the change of data, so the view rendered with v-for will be updated immediately.
The array method of the source array will be modified:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
Array methods that do not modify the source array:
- filter()
- concat()
- slice
It should be noted that Vue cannot be detected and will not trigger view update in the following changed arrays:
- Set items directly through the index, such as app books[3] = { … }.
- Modify the length of the array, such as tap p.books length = 1.
To solve the first problem, you can use Vue's built-in set method:
Vue.set(app.books,3,{ id:"3", name:"Lord of mystery" })
Sort cases:
<div id="app"> <ul> <li v-for="(p, index) in persons"> {{p.id}}--{{p.name}}--{{p.age}} </li> </ul> <button @click="sortType(1)">Ascending by age</button> <button @click="sortType(2)">In descending order of age</button> </div>
new Vue({ data: { sortType: 1, // Sort type, 1: ascending, 2: descending persons: [ {id: 1, name: 'Tom', age: 15}, {id: 2, name: 'Jack', age: 12}, {id: 4, name: 'Bob', age: 17}, {id: 6, name: 'Rose', age: 16}, {id: 8, name: 'Else', age: 13} ], }, methods: { sortType () { arr.sort((p1, p2) => { if (sortType===1) { // Ascending order return p1.age - p2.age } else { // Descending order return p2.age - p1.age } }) return arr } }, })
6.8 v-once
vue is a two-way binding. If the data changes, the view will also change. If you don't want the view in vue to change, you can use the v-once instruction.
Function: the element or component that defines it is rendered only once, including all child nodes of the element or component. After the first rendering, it will not be re rendered with the change of data, and will be regarded as static content.
<div id="app"> <p v-once>raw data: {{ name }}</p> <p>Current data: {{ name }}</p> </div>
let app = new Vue({ el: '#app', data: { name: "zhangsan", } });
At this point, we enter in the console
app.name="lisi"
You will find that the content in the first p tag has not changed. The contents of the second P tag will change as the data changes. This is the use of v-once.
7. Form data binding
Vue provides the v-model instruction, which is used to bind data on form elements in both directions. For example, when used on the input box, the input content will be mapped to the bound data in real time. The input box in the form has been demonstrated in our previous case. We won't talk more here. Next, let's talk about other form elements,
7.1 radio box
If multiple radio boxes want to be mutually exclusive, that is, if they want to be a group, their v-model values must be equal.
<div id="app"> <input type="radio" value="html" v-model="inputdata" />html<br> <input type="radio" value="css" v-model="inputdata"/> css<br> <input type="radio" value="javascript" v-model="inputdata" />javascript<br> </div>
var app = new Vue({ el:"#app", data:{ inputdata:"javascript" } })
When the data in data is consistent with the value value of the radio button, the radio button will be selected.
7.2 check box
Check boxes can be used separately or in combination.
7.2.1 use alone
In the input tag, use v-model to bind a Boolean value. When it is checked, the value of the bound data becomes true; otherwise, it becomes false;
<div id="app"> <input type="checkbox" v-model="isChecked"/>Consent agreement<br> <p>Selection status:{{isChecked}}</p> </div>
var app = new Vue({ el:"#app", data:{ isChecked:false } })
7.2.2 combined use
When used in combination, v-model and value are also used together. Multiple check boxes are bound to data of the same array type. Note that they must be the same and of the same array type. Examples are as follows:
<div id="app"> <input type="checkbox" v-model="checkData" value="legend of chusen"/>legend of chusen<br> <input type="checkbox" v-model="checkData" value="Infinite terror"/>Infinite terror<br> <input type="checkbox" v-model="checkData" value="Thriller paradise"/>Thriller paradise<br> <p> Your choice is:{{checkData}} </p> </div>
var app = new Vue({ el:"#app", data:{ checkData:["Infinite terror","Thriller paradise"]; } })
When the multi check box is checked, its value will be push ed into the bound data checkData. This process is two-way, that is, modifying the value in checkData will also update the selection status of the multi check box.
7.3 drop down box
The drop-down box is also divided into single selection and multiple selection
7.3.1 single choice
Let's look at the example code first
<div id="app"> <select v-model="isSelected"> <option value="legend of chusen">legend of chusen</option> <option value="Infinite terror">Infinite terror</option> <option value="Imperceptible">Thriller paradise</option> </select> </div>
var app = new Vue({ el:"#app", data:{ isSelected:"legend of chusen" } })
The drop-down box is the drop-down list, and the v-model needs to be bound in the select tag. The option tag is a required option. When learning HTML, we know that the value of select is determined by the value attribute of the selected option. But in vue, if we don't have value, the data will match the text content of the selected option. That is, if the third option is selected, the value of isSelected will be imperceptible rather than thriller park
7.3.2 multiple selection
Add the multiple attribute to the select tag to select more than one. At this time, the v-model is bound with an array, which is used with the check box
The method is similar.
<div id="app"> <select v-model="isSelected" multiple> <option value="legend of chusen">legend of chusen</option> <option value="Infinite terror">Infinite terror</option> <option value="Imperceptible">Thriller paradise</option> </select> <p> Your choice is:{{checkData}} </p> </div>
var app = new Vue({ el:"#app", data:{ isSelected:["legend of chusen","Infinite terror"] } })