Vue 基础2

1. 计算属性:  缓存,

计算属性会把第一次计算的结果存在到缓存中,如果依赖的数据没有发生变化,再次使用计算属性时,会从缓存中取上次计算的结果,这样性能就提高。 使用场景:依赖的数据不经常发生变化时,使用计算属性可以提高渲染性能.
<script>
        var vm = new Vue({
            el: "#app",
            data: {
                msg: "hello"
            },
            // methods中定义是方法
            methods: {
                sayHello(){
                    console.log("看看方法执行了几遍?")     //执行了两遍
                    return this.msg;
                }
            },
            // computed中定义计算属性
            computed: {
                // 计算属性:本质也是一个函数。定义时和方法一样。
                getMsg(){
                    console.log("看看计算属性执行了几遍?")    //执行了一遍
                    return this.msg;
                }
            }
        })
    </script>
1.1  计算属性 深入  (set,get)
  
 <script>
        var vm = new Vue({
            el: "#app",
            data: {
                firstName: '张',
                lastName: '三'
            },
            computed:{
                // 这种写法,相当于只设置了get,所以只能获取值,不能设置值。
                // Computed property "fullName" was assigned to but it has no setter
                /* fullName(value){
                    return this.firstName + this.lastName
                } */

                fullName: {
                    // get()用来给计算属性获取值
                    get(){
                        return this.firstName + this.lastName;
                    },
                    // set()用来给计算属性设置值,参数是新值。
                    set(newValue){
                        // 新的全称,需要拆开
                        this.firstName = newValue.charAt(0)
                        this.lastName = newValue.slice(1)
                    }
                }
            }
        })
    </script>
 
 
posted @ 2021-11-30 10:37  水波凌步  阅读(40)  评论(0)    收藏  举报