My Vue study notes
The MVVM thought
MVVM is short for model-view-viewModel, that is, model-view-viewmodel. The Model is the data View that is passed from the back end is the page View that we see and the Model is a core part of the MVVM idea. It links the View and the Model and acts as a bridge between them. It has two directions: One is to convert Model into View, that is, the data transmitted by the back end into the page to be seen; the other is to convert View into Model, that is, the content operated by the user on the page is converted into the data at the back end. These two functions are realized through data binding and DOM event monitoring, which is called bi-directional data binding. As shown in the figure:
Create instances, data bindings, directives, and events
Create an instance
Vue creates an instance as follows:
<div id="app">
{{myData}}
</div>
<script>
var vueApp = new Vue({
el:'#app',
data:{
myData:'Hello World'
myData2:'Fuck World'}}); </script>Copy the code
El and data in the code are attributes of the vUE instance. El is used to specify the EXISTING DOM element in the page to mount the Vue instance, and data is the data that vUE needs to bind in both directions.
Data binding
When mounted, attributes of vue instance.$attributes of vue instance can be accessed using syntax such as vueApp.$el, whereas attributes of data can be accessed using syntax such as vueapp.mydata
Lifecycle hook
Vue lifecycle hooks are defined methods that execute at some stage in the lifecycle of a VUE object. From the time a Vue instance object is initialized to the time it is destroyed, the object follows a different life stage. I’ve captured a famous hook diagram of the life cycle:
- BeforeCreate: The hook function for creating vUE instances
- Created: A VUE instance is created, but not yet mounted to the DOM element of the page
- BeforeMount: Starts mounting
- Mounted: Mounts compiled HTML to the page and mounts only once during the entire lifecycle
- beforeUpdate
- updated
- BeforeDestroy: Hook function executed before vue instance is destroyed
- The hook function that executes when the instance is destroyed
There are many phases to the VUE lifecycle, but we use these three phases most often:
- created
- mounted
- beforeDestroy
For example:
var vueApp = new Vue({
el:'#app',
data:{
myData:'Hello World'
},
created:function () {
alert('Vue instance created, but not yet mounted to DOM element');
},
mounted:function () {
alert('Vue instance has been mounted to DOM'); }});Copy the code
For the example page above, when you open the browser, the message “Vue instance has been created but not mounted to the DOM element” will pop up. For the created stage, the Vue instance has actually been created but not mounted to the DOM element. The mounted phase is called after the vue instance is mounted to the DOM. The first business logic starts in this phase. BeforeDestory This is the stage before the vUE instance is destroyed. Some listener events are unbound during this stage.
Text interpolation
For this example, we’ll see the word “Hello World” on the page, and in the HTML, we’ll write this syntax:
<div id="app">
{{myData}}
</div>
Copy the code
This syntax is Vue’s text interpolation syntax, which supports a single expression, but only a single expression:
{{1 < 0? MyData :myData2}} This is a teradata operator expression. It is legal because it is a single expression. Var a = 6 is a declarative expression + an assignment expression. We mentioned that Vue's text interpolation syntax only supports a single expression, so this will cause an errorCopy the code
The filter
Vue. Js support add {{}} interpolation on the tail of a small pipe “|” for data filtering, often used for formatting text, such as letters all caps one thousand separated by a comma, currency, etc., also supports the filter series written, ginseng, and so on. Let’s look at an example where the page displays the current time in real time:
<div id="app">
{{currentDate | format}}
</div>
<script>
function formatTime(value) {
return value <10 ? '0'+value : value;
}
var vueApp = new Vue({
el:'#app',
data:{
currentDate: new Date()
},
filters:{
format:function(currentDate) { var date = new Date(currentDate); var year = date.getFullYear(); Var month = formatTime(date.getMonth()+1); Var days = formatTime(date.getDate()); Var hours = formatTime(date.gethours ()); Var minutes = formatTime(date.getminutes ()); Var seconds = formatTime(date.getseconds ()); // Get the current secondreturn 'Current time is :'+year+'years'+month+'month'+days+'day'+hours+'when'+minutes+'points'+seconds+'秒'
}
},
mounted:function () {
this.timer = setInterval(()=>{
this.currentDate = new Date();
},1000)
},
beforeDestroy:function() { window.clearInterval(this.timer); }}); </script>Copy the code
We can also pass parameters to the filter by making a small change to the code:
<div id="app">
{{currentDate | format('Current time is'.':')}}
</div>
<script>
function formatTime(value) {
return value <10 ? '0'+value : value;
}
var vueApp = new Vue({
el:'#app',
data:{
currentDate: new Date()
},
filters:{
format:function(currentDate,arg1,arg2) { var date = new Date(currentDate); var year = date.getFullYear(); Var month = formatTime(date.getMonth()+1); Var days = formatTime(date.getDate()); Var hours = formatTime(date.gethours ()); Var minutes = formatTime(date.getminutes ()); Var seconds = formatTime(date.getseconds ()); // Get the current secondreturn arg1+arg2+year+'years'+month+'month'+days+'day'+hours+'when'+minutes+'points'+seconds+'秒'
}
},
mounted:function () {
this.timer = setInterval(()=>{
this.currentDate = new Date();
},1000)
},
beforeDestroy:function() { window.clearInterval(this.timer); }}); </script>Copy the code
We added parameters to the filter and got the same result as before. It is important to note: the first filter function of the corresponding to the incoming value is the data in front of the “|” attribute values, in this case, i.e., currentDate, and is not a parameter, the incoming parameter is a function of the second transfer value and future value. Filters can also use “series writing” at the same time, such as: {{currentDate | filter1 | filter2 | filter3}}, the method of filter will be executed in sequence, and they are defined in the attribute of the vue filters.
Instructions and events
One of the advantages of the VUE framework is that it supports instruction manipulation, which is one of the most commonly used features in VUE templates. It eliminates complex DOM apis and is extremely easy to remember and understand. Let’s take a quick look at some commands:
-
v-text
The function of V-text is to parse text in exactly the same way that text interpolation {{}} does
-
v-html
Parse the content into HTML
-
v-bind
Dynamically update HTML elements, such as IDS, classes, and so on
-
v-on
Used to bind event listeners
Let’s continue to use examples to briefly understand these command events.
<style>
.active{
background: red;
height: 1em;
}
</style>
---------------------------------------------------------------
<div id="app"> v-text: <br> {{apple}} <br> <! -- V-text works the same as text interpolation --> <span v-text="apple"></span>
v-html: <br>
<span v-html="banana"></span> <br>
v-bind: <br>
<div v-bind:class="className"<br> <div :class="className"></div>
v-on: <br>
<button v-on:click="plusOne">{{originalNum}}</button> <br> <button @click="plusOne">{{originalNum}}</button>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
apple:'apple',
banana:' > ',
className:'active',
originalNum:0
},
methods:{
plusOne:function() { this.originalNum = this.originalNum + 1; }}}); </script>Copy the code
For both v-bind and V-ON instructions, there is a shorthand format for the response, as in the example:
<div v-bind:class="className"></div> can be shortened to: <div :class="className"></div>
<button v-on:click="plusOne"</button> < {{originalNum}}</button"plusOne">{{originalNum}}</button>
Copy the code
Calculate attribute
For the string ‘123,456,789’ we want to change the string to: ‘321,654,987’. Here’s an example:
<div id="app">
{{text.split(', ').map((e)=>{return e.split(' ').reverse().join(' ')}).join(', ')}}
</div>
<script>
var app = new Vue({
el:'#app',
data:{
text:'123456789'}}); </script>Copy the code
We see this program in the mind must be a mother to sell batch, although there is no problem with the program, also in line with the syntax of text interpolation, but it seems to feel very headache, and the code is not easy to maintain. We can optimize the content by creating a function and placing it in the Methods property:
<div id="app"> <! -'123456789'This string becomes'321654987'<br> {{text.split(', ').map((e)=>{return e.split(' ').reverse().join(' ')}).join(', '<br> {{reverseMethod()}} <br> </div> <script> var app = new var ({el:'#app',
data:{
text:'123456789'
},
methods:{
reverseMethod:function() {/ / /'123', 456,'789']
return this.text.split(', ').map((e)=>{
return e.split(' ').reverse().join(' ');
}).join(', '); }}}); </script>Copy the code
Instead of defining methods in methods and calling them, we can also use computed properties:
<div id="app"> <! -'123456789'This string becomes'321654987'<br> {{text.split(', ').map((e)=>{return e.split(' ').reverse().join(' ')}).join(', '<br> {{reverseText}} </div> <script> var app = new Vue({el:'#app',
data:{
text:'123456789'
},
methods:{
reverseMethod:function() {/ / /'123', 456,'789']
return this.text.split(', ').map((e)=>{
return e.split(' ').reverse().join(' ');
}).join(', ');
}
},
computed:{
reverseText:function () {
return this.text.split(', ').map((e)=>{
return e.split(' ').reverse().join(' ')
}).join(', '); }}}); </script>Copy the code
We have defined methods in computed properties in the VUE example, and at first glance there is no difference between methods. In fact, methods can do everything that can be done with computed properties, but there are differences. The function of this example is to calculate the sum of the prices of the shopping cart. The specific code is as follows:
<div id="app">
{{prices}}
</div>
<script>
var app2 = new Vue({
el:'#app2',
data:{
msg:'The sum of the two shopping carts is :'}}); var app = new Vue({ el:'#app', data:{// shopping cart 1 package1:[{name:'iphone',
price:6999,
count:2
},
{
name:'ipad', price:3299, count:2}], //'XiaoMi',
price:999,
count:6
},
{
name:'ipod',
price:1099,
count:2
}
]
},
computed:{
prices:{
get:function() { var prices = 0; // The sum of the first shopping cart pricesfor(var i = 0; i<this.package1.length; i++){ prices += this.package1[i].price * this.package1[i].count; } // The sum of the first and second shopping cartsfor(var j = 0; j<this.package2.length; j++){ prices += this.package2[j].price * this.package2[j].count; }return app2.msg+prices;
},
set:function (options) {
if(options.package === 'package1') {for(var i = 0; i<this.package1.length; i++){if(this.package1[i].name === options.name){
this.package1[i].price = options.price;
this.package1[i].count = options.count;
break; }}}else if(options.package === 'package2') {for(var i = 0; i<this.package2.length; i++){if(this.package2[i].name === options.name){
this.package2[i].price = options.price;
this.package2[i].count = options.count;
break; }}}}}}}); </script>Copy the code
Every calculated property has a getter and setter methods. When we call only the method name of the calculated property, we actually call the get method of the property. When it is necessary to set some parameters, we can also provide a set method to manually modify the calculated property. In addition, in this example, we can see that the calculated prices attribute is not only dependent on the current Vue object but also on other instances. Although App2 is not mounted to the DOM, the results of the execution indicate that the calculated prices attribute can be dependent on other instances. The code execution results are as follows:
Calculate attributes and methods
Let’s start with an example:
<div id="app">
{{text}} <br>
{{getNow()}} <br>
{{now}} <br>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
text:666
},
methods:{
getNow:function () {
return Date.now();
}
},
computed:{
now:{
get:function () {
returnDate.now(); // Get the timestamp from 1970 to the present}}}}); </script>Copy the code
We have defined a function to get the timestamp from 1970 to the present in both methods and calculated properties. The code runs as follows:
V-bind’s class is bound to style
The v-bind function can be described in one sentence: Bind live attributes. Let’s review it with a simple example:
<div id="app">
<a v-bind:href="url"</a> </div> <script> var app = new Vue({el:'#app',
data:{
url:'http://www.baidu.com'}}); </script>Copy the code
Click the link on the page and it will jump to Baidu.
V-bind class binding
V-bind Binds the class object syntax
See the sample:
<style>
.red{
background: red;
}
.blue{
background: blue;
}
</style>
--------------------------------------------------
<div id="app"> v-bind: <br> <button V-bind :class="{red:isRed,blue:isBlue}" v-on:click="transColor">clickMe</button>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
isRed:true,
isBlue:false,
},
methods:{
transColor:function () {
this.isRed = !this.isRed;
this.isBlue = !this.isBlue;
}
}
});
</script>
Copy the code
V-bind :class uses object syntax. The key of the object is the name of the class and the value of the object is a Boolean value. If the value is true, it is bound to the class name.
The V-bind binding evaluates the property syntax
See the sample:
<style>
.red{
width: 100px;
height: 100px;
background: red;
}
</style>
-----------------------------------------------
<div id="app"< span style = "box-sizing: border-box; color: RGB (50, 50, 50); line-height: 22px; font-size: 14px! Important; word-wrap: inherit! Important;" Value is Boolean <br> <div V-bind :class="computedClass"></div>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
isRed:true,
},
computed:{
computedClass:function () {
return {
red:'isRed'}}}}); </script>Copy the code
In the example, v-bind:class binds the evaluated attribute, but even if it is a evaluated attribute, the result is an object, where key is the class name and value is a Boolean. Likewise, when value is true, the element carries the class, and when value is false, the element does not
V-bind binds the class array syntax
See the sample:
<style>
.first{
font-size: 32px;
color: red;
}
.second{
background: # 000;
}
</style>
---------------------------------------
<div id="app"> bind class array syntax: The members of an array are attributes in data that correspond directly to the class name <br> <div V-bind :class="[classOne,classTwo]">VUE is cool! </div> </div> <script> var app = new Vue({ el:'#app',
data:{
classOne:'first',
classTwo:'second'}}); </script>Copy the code
The syntax of the v-bind class array is simpler than that of the previous one. The members of the array are the properties of data, which correspond directly to the class name
V-bind bind inline style
In addition to binding classes,v-bind can also bind inline styles
<div id="app"Br > <div v-bind:style= "class =" class "style=" box-sizing: border-box! Important; word-wrap: break-word! Important"{'color':color,'fontSize':fontSize}">VUE is cool! </div> </div> <script> var app = new Vue({ el:'#app',
data:{
color:'red',
fontSize:'32px'}}); </script>Copy the code
In addition to this object syntax, bind inline styles also support “array” syntax, but this syntax is said to be silly because no one can write styles separately, so I won’t show it here. It is important to note that CSS property names are either camel or delimited, but it is recommended to use the camel form ~~~~