VueDay05计算属性

VueDay05计算属性

利用计算属性的使用,缓存计算结果,提高性能。计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <!-- 缓存计算结果 -->
        <div id="app">
            <!-- 一般情况下写法 -->
            <h1>{{firstname+lastname}}</h1>
            <!-- 计算属性 -->
            <h1>{{fullname}}</h1>
            <!-- 逆序显示单词 -->
            <h1>{{word.split("").reverse().join("")}}</h1>
            <h1>{{reverseWord}}</h1>
            <h1>循环偶数的年龄</h1>
            <ul>
                <li v-for="item,index in oddStudents">
                    <h3>{{item.studentName}}</h3>
                    <h4>{{item.age}}----{{item.school}}</h4>
                </li>
            </ul>
        </div>
        <script type="text/javascript">
            var app =new Vue({
                el:"#app",
                data:{
                    firstname:"",
                    lastname:"",
                    word:"music",
                    students:[
                        {
                            studentName:"小明",
                            age:16,
                            school:"清华",
                            imgheader:"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2369017631,3935728806&fm=26&gp=0.jpg"
                        },
                        {
                            studentName:"小黑",
                            age:17,
                            school:"北大"
                        },
                        {
                            studentName:"小红",
                            age:18,
                            school:"浙大"
                        },
                        {
                            studentName:"小红",
                            age:15,
                            school:"浙大"
                        }
                    ]
                },
                computed:{
                    fullname:function(){
                        console.log(this)
                         /* computed属性:会将计算的结果进行缓存,只要this.firstname和this.lastname
                         的值不改变 就不会重新计算*/
                        return this.firstname+this.lastname
                    },
                    reverseWord:function(){
                        return this.word.split("").reverse().join("")
                    },
                    oddStudents:function(){
                     let results =this.students.filter((item,i)=>{
                            return item.age%2==0
                        })
                        return results
                    }
                }
            })
        </script>
    </body>
</html>

 

posted @ 2020-09-17 11:35  peifengyang  阅读(203)  评论(0编辑  收藏  举报