Interpolation operation of template syntax
(1)v-html inserts HTML text into the tag;
(2)v-text inserts ordinary text into the label (the label cannot be parsed);
(3)v-pre directly displays the syntax on the interface;
(4)v-cloak hides the display of beard syntax on the interface before rendering the data to the page.
The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> [v-cloak] { display: none; } </style> </head> <body> <div id="app"> <div v-html="htmlTxt"></div> <div v-text="textTxt"></div> <div v-pre>{{123}}</div> <div v-cloak>hello {{textTxt}}</div> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> let vm = new Vue({ el: '#app', data: { htmlTxt: '<p><strong>I am html</strong></p>', textTxt: 'Vue' } }) </script> </html>
key attribute in v-for
<div id="app"> <input type="text" v-model="txtVal"> <button @click="handleClick">Button</button> <ul> <li v-for="i,k in list" :key="i"> <input type="checkbox"> {{ i }} </li> </ul> </div> <script> var vm = new Vue({ el:"#app", data:{ list:['html', 'css', 'javascript', 'jquery'], txtVal:"" }, methods:{ handleClick(){ this.list.unshift(this.txtVal) } } }) </script>
It is officially recommended that we add a key attribute to the corresponding element or component when using v-for.
Why do you need this key attribute
(1) This is actually related to the Diff algorithm of Vue's virtual DOM.
When there are many same nodes in a layer, that is, list nodes, we insert a new node into the list
(2) Add an F between B and C. when the Diff algorithm is executed by default, it is as follows:
That is, updating C to F, D to C, E to D, and finally inserting a new E is too inefficient.
When we use the key to uniquely identify each node: the Diff algorithm will use the key as the identification to identify this node, find the correct location area and insert a new node. Therefore, the role of the key is to efficiently update the virtual DOM.
be careful:
(1) The key attribute is the basis for judging whether the DOM node needs to be updated. If the content of the key value changes, the DOM needs to be updated (the DOM is rebuilt after deletion). If the content does not change, the DOM node does not need to be operated;
(2)key is used to efficiently update the virtual DOM.
Use of reduce method
Use the reduce method to traverse each element of the array. The result of the reduce() call returns a final value (the last return value).
var arr = [ {name: 'Vuejs introduction', price: 99, count: 3}, {name: 'Vuejs bottom', price: 89, count: 1}, {name: 'Vuejs From getting started to giving up', price: 19, count: 5}, ] //Array name. Reduce (callback function, initial value of pre) arr.reduce(function(pre, current){ // When the reduce method is called, it will traverse each element of the array arr, and execute the code here once for each element // current represents the element currently being traversed // pre is the value of the last return of this function // !!! Because there is no previous return value in the first traversal, the second parameter is given to set the initial value of pre console.log(pre, current) return 10 },0) //!!! And the reduce method will eventually return the last return value
Console output:
0 {name: "Vuejs introduction", price: 99, count: 3} 10 {name: "Vuejs bottom", price: 89, count: 1} 10 {name: "Vuejs From getting started to giving up", price: 19, count: 5}
Use of Vue's calculated attribute computed
<div id="app"> {{total}} </div> <script> var vm = new Vue({ el:"#app", data:{ arr: [ {name: 'Vuejs introduction', price: 99, count: 3}, {name: 'Vuejs bottom', price: 89, count: 1}, {name: 'Vuejs From getting started to giving up', price: 19, count: 5}, ] }, computed:{ //The method in computed must have a return value! This return value will be referenced by {{total}} in the view in the future total(){ var a = this.arr.reduce(function(pre, current){ console.log(pre, current) // var total = current price*count + last total var total = current.price*current.count + pre return total },0) return a } } }) </script>
The computed internal method has the function of caching
The following code is called three times in total, but only executed once. This is because the cache of the calculated internal method works
<div id="app"> {{total}} {{total}} {{total}} {{getTotal()}} {{getTotal()}} {{getTotal()}} </div> <script> var vm = new Vue({ el:"#app", data:{ arr: [ {name: 'Vuejs introduction', price: 99, count: 3}, {name: 'Vuejs bottom', price: 89, count: 1}, {name: 'Vuejs From getting started to giving up', price: 19, count: 5}, ] }, methods:{ getTotal(){ console.log("getTotal") var a = this.arr.reduce(function(pre, current){ // var total = current price*count + last total var total = current.price*current.count + pre return total },0) return a } }, computed:{ //The method in computed must have a return value! This return value will be referenced by {{total}} in the view in the future total(){ console.log("total") var a = this.arr.reduce(function(pre, current){ // var total = current price*count + last total var total = current.price*current.count + pre return total },0) return a } } }) </script>
Another way to write the computed internal method (get and set)
.... computed:{ //The method in computed must have a return value! This return value will be referenced by {{total}} in the view in the future total:{ get(){ console.log("total_get") var a = this.arr.reduce(function(pre, current){ // var total = current price*count + last total var total = current.price*current.count + pre return total },0) return a }, set(){ console.log("total_set") }, } } ... vm.total = 3 //Trigger call set method
Summary:
1. Definition: the attribute to be used does not exist, but must be calculated from the existing attribute.
2. Principle: the bottom layer uses getter s and lsetter s provided by objcet.defineproperty method.
3. When does the get function execute? (1) It is executed once on the first reading. (2) When the dependent data changes, it will be called again.
4. Advantages:
Compared with the methods implementation, there is an internal level storage mechanism (reuse), which is more efficient and convenient for debugging.
5. Note:
(1) The calculated attributes will eventually appear on the vm and can be read and used directly.
(2) If the calculation attribute is to be modified, the set function must be written to respond to the modification, and the data in the set will change.
Principle of v-model
v-model essentially contains two operations:
(1)v-bind binds the value attribute of the input element
(2) The v-on instruction binds the input event of the input element
Namely:: value="txtVal" and @ input="handleInput"
<div id="app"> <!-- <input type="text" v-model="txtVal"> --> <input type="text" :value="txtVal" @input="handleInput"> <p>{{ txtVal }}</p> </div> <script> var vm = new Vue({ el:"#app", data:{ txtVal:"" }, methods:{ handleInput(e){ console.log(e) this.txtVal = e.target.value } } }) </script>
Namely:
<input type="text" v-model="textVal"/> <!-- Equivalent to --> <input type="text" v-bind:value="textVal" v-on:input="textVal = $event.target.value"/>
Common operations of array
push (return array length)
unshift (return array length)
shift (return deleted value)
pop (return deleted value)
splice, concat (return new array)
var arr = [1, 2, 3] // Adds a number to the last bit of the array arr.push(4) // [1, 2, 3, 4] // Delete the last number in the array arr.pop() // [1, 2, 3] console.log(arr) // Adds a number to the first digit of the array arr.unshift(0) console.log(arr) // Delete the first element of the array arr.shift() console.log(arr) // splice // Delete first element arr.splice(1, 2) console.log(arr) arr.splice(1, 2, 2, 4, 5) console.log(arr) // Merge array console.log([1, 6].concat([5, 7]))
reduce (calculation)
filter
map (set)
var arr = [1, 2, 3] // Calculate total var ret1 = arr.reduce((pre, current)=>{ pre += current return pre }, 0) console.log(ret1) // 6 // filter var ret2 = arr.filter(item =>{ return item > 2 }) console.log(ret2) // [3] // map var ret3 = arr.map(item =>{ return {id:item} }) console.log(ret3) // [{id: 1}, {id: 2}, {id: 3}]
Array de duplication
var arr2 = [1, 2, 3, 1, 6, 2, 3] //ES6 consoloe.log([...new Set(arr2)]) console.log(Array.from(new Set(arr2))) var newArray = []; for(var i=0; i<arr2.length; i++){ if(newArray.indexOf(arr2[i])==-1){ newArray.push(arr2[i]) } } console.log(newArray) var newArray2 = []; var obj = {}; for(var i=0; i<arr2.length; i++){ if(!obj[arr2[i]]){ //If it is not in obj, it means that there is no duplicate data, and key value pairs are added to the object obj[arr2[i]] = arr2[i] newArray2.push(arr2[i]) } } console.log(newArray2)
Vue filters and global filters
use
Vue's filter is used to do some processing before data display
<div id="app"> <!-- {{ Variable name | Filter name }} --> <p>{{ num | formatNum }}</p> </div> <script> var vm = new Vue({ el:"#app", data:{ num:10 }, filters:{ formatNum(val){ // This parameter receives the variable data before the | symbol return val + 50 //The value after return is the value to be displayed on the page in the future (that is, the filtered value) } } }) </script>
Filter a timestamp:
<div id="app"> <!-- {{ Variable name | Filter name }} --> <p>{{ timestamp | formatDate }}</p> </div> <script> // var timestamp = new Date().getTime() / / get timestamp // console.log("date is:", timestamp) var vm = new Vue({ el:"#app", data:{ timestamp:new Date().getTime() }, filters:{ formatDate(val){ // This parameter receives the variable data before the | symbol var now = new Date(val) var year=now.getFullYear(); var month=now.getMonth()+1; var date=now.getDate(); var hour=now.getHours(); var minute=now.getMinutes(); var second=now.getSeconds(); return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; } } }) </script>
Global filter
Filters shared by multiple app s can be written as global filters
<div id="app"> <!-- {{ Variable name | Filter name }} --> <p>{{ timestamp | formatDate }}</p> </div> <div id="app2"> <!-- {{ Variable name | Filter name }} --> <p>the second: {{ timestamp | formatDate }}</p> </div> <script> //Global filter // Vue.filter("filter name", (VAL) = > {}) Vue.filter("formatDate",(val)=>{ var now = new Date(val) var year=now.getFullYear(); var month=now.getMonth()+1; var date=now.getDate(); var hour=now.getHours(); var minute=now.getMinutes(); var second=now.getSeconds(); return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; }) var vm2 = new Vue({ el:"#app2", data:{ timestamp:new Date().getTime() } }) // var timestamp = new Date().getTime() / / get timestamp // console.log("date is:", timestamp) var vm = new Vue({ el:"#app", data:{ timestamp:new Date().getTime() }, // filters:{ // formatDate(val){ // This parameter receives the variable data before the | symbol // var now = new Date(val) // var year=now.getFullYear(); // var month=now.getMonth()+1; // var date=now.getDate(); // var hour=now.getHours(); // var minute=now.getMinutes(); // var second=now.getSeconds(); // return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; // } // } }) </script>
That's all for the second day of Vue introduction.
Data document address: Front end Development Basics: Day02Vue basics.pdf