Recently I was looking at the knowledge of vue framework, and then I was puzzled by the writing method of this in one example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="demo"> search: <input type="text" v-model="searchName"> <ul> <li v-for="(p,index) in filterPersons" :key="index"> {{index}} --- {{p.name}} --- {{p.age}} </li> </ul> <button @click="setOrderType(1)">Age ascending order</button> <button @click="setOrderType(2)">Age descending order</button> <button @click="setOrderType(0)">Original order</button> </div> <script src="../js/vue.js"></script> <script> var vm = new Vue({ el: '#demo', data: { searchName: '', /** * Sort type: * 0 - Original order * 1 - Age ascending order * 2 - Age descending order */ orderType: 0, persons: [{ name: 'Tom', age: 18 }, { name: 'Jack', age: 20 }, { name: 'Bob', age: 16 }, { name: 'Kaka', age: 25 }, { name: '22', age: 23 }, { name: '33', age: 18 }, { name: 'Shadow', age: 21 }, { name: 'Good', age: 18 }, { name: 'Lily', age: 20 }, { name: 'Lena', age: 19 } ] }, computed: { filterPersons() { // Retrieve relevant data const { searchName, persons, orderType } = this; let flag; flag = persons.filter(p => p.name.indexOf(searchName) !== -1); if (orderType !== 0) { flag.sort(function (p1, p2) { if (orderType === 2) { return p2.age - p1.age; } else { return p1.age - p2.age; } }); } return flag; } }, methods: { setOrderType(orderType) { this.orderType = orderType; } } }); </script> </body> </html>
In this pile of code, the first line of the filterPerson function assigns this value, creating an object and assigning it to a constant
In some tutorials, it means that this is the data to be used
In fact, it's a simplification, because I'll comment it out later, and then add this in front of each variable to still run
computed: { filterPersons() { // Retrieve relevant data // const { // searchName, // persons, // orderType // } = this; let flag; flag = this.persons.filter(p => p.name.indexOf(this.searchName) !== -1); if (this.orderType !== 0) { flag.sort(function (p1, p2) { if (this.orderType === 2) { return p2.age - p1.age; } else { return p1.age - p2.age; } }); } return flag; } }
Therefore, in this place, the data to be used is put in this in advance, mainly because there are no such variables in the function itself, so using it directly inside the function will report an error, so you need to get it from the external vue instance. If not, write more this.