在方法中,this指向该方法所属的组件。可以使用this访问data对象的属性和其他方法:
<!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>this</title> </head> <body> <div id="app"> <p>所有正数的和:{{getPositiveNumbersSum()}}</p> </div> <script src="https://unpkg.com/vue"></script> <script> new Vue({ el: "#app", data: { numbers: [-3, -2, -1, 0, 1, 2, 3] }, methods: { getPositiveNumbers() { return this.numbers.filter((number) => number > 0); }, getPositiveNumbersSum() { return this.getPositiveNumbers().reduce((sum, val) => sum + val); } } }) </script> </body> </html>