参考书籍《Vue.js快跑:构建触手可及的高性能Web应用》第1章 Vue.js基础-----1-12this

在方法中,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>

 

posted @ 2021-06-18 10:33  {颜逸}  阅读(39)  评论(0编辑  收藏  举报