vue3+ts学习(四):computed与watch

68 阅读1分钟

Computed计算处理后的属性,具有缓存性

      <h2>{{reverseWord}}</h2>
      <h2>{{reverseWord}}</h2>
      <h2>{{reverseWord}}</h2>
      <h2>{{reverseWord}}</h2>
      <h2>{{reverseWord}}</h2>
      
      data(){
        return{
          message:"Hello World"
        }
      },
      computed:{
        reverseWord(){
          console.log("走一次");  //有缓存 只执行一次
          return this.message.split(" ").reverse().join(" ")
        }
      }
      

Computed还有get和set的写法

      data(){
        return{
          firstName:"Hello",
          lastName:"World",
        }
      },
      methods:{
        updateName(){
          this.fullName = this.fullName + 1
        }
      },
      computed:{
        fullName:{
          // 一般不会直接修改计算属性,所以set基本不会使用,但是不能没有set,没有了就算改变firstName也不能修改fullName了
          set(newVal){
            console.log("调用了set")
            const msg = newVal.split(" ")
            this.firstName = msg[0]
            this.lastName = msg[1]
          },
          get(){
            console.log("调用了get")
            return `${this.firstName} ${this.lastName}`
          }
        }
      }

watch用于监听属性变化,可以配置深度监听对象

      watch:{
        // 写法一
        info:{
          handler(newVal,oldVal){
            // 引用数据类型的地址是一样的,是没有进行拷贝的,所以拿不到旧的值 oldVal == newVal
            console.log('oldVal: ', oldVal);  
            console.log('newVal: ', newVal);
          },
          deep:true,    //开启深度监听
          // immediate:true  //初始化立即执行一次handler不管有没有改变
        },
        
        // 写法二
        "info.name":function(newVal,oldVal){
            console.log('oldValName: ', oldVal);  //也可以这样写 精准监听某个属性
            console.log('newValName: ', newVal);
        }
      },
      
      
      created(){
        // 写法三
        // 在created中手动添加监听,这个监听回调一个函数 调用这个函数可以解绑该监听
        const unwatch = this.$watch("info",(newVal,oldVal)=>{
          console.log('oldValCreated: ', oldVal);  //
          console.log('newValCreated: ', newVal);
        },{deep:true,immediate:true}
        )
        // unwatch()
      }