vue列表排序實現中的this問題


最近在看vue框架的知識,然后其中有個例子中的this的寫法讓我很疑惑

<!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)">年齡升序</button> <button @click="setOrderType(2)">年齡降序</button> <button @click="setOrderType(0)">原本順序</button> </div> <script src="../js/vue.js"></script> <script> var vm = new Vue({ el: '#demo', data: { searchName: '', /** * 排序種類: * 0 - 原本順序 * 1 - 年齡升序 * 2 - 年齡降序 */ 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() { // 取出相關的數據 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>

在這堆代碼中的filterPerson函數的第一行進行了this的賦值,創建了一個對象賦給了一個常量 在一些教程中表示這是取出要用的數據 其實算是簡化操作,因為后面我將其注釋掉,然后在每個變量前面加上this依舊可以跑起來

computed: { filterPersons() { // 取出相關的數據 // 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; } }

所以,在這個地方是將要用的數據事先放在了this中, 主要是函數中本身沒有這幾個變量,所以直接在函數內部使用是會報錯的,因此需要去外面的vue實例中獲取。如果不這么做,要多寫很多個this


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM