首页 > 编程技术 > js

Vue中监视属性和计算属性区别解析

发布时间:2022-10-31 15:17 作者:澜璨

计算属性

顾名思义,计算属性就是计算出来的属性,英文名儿computed
这里要和data和methods里的东西区分,data里的属性,methods里的函数,你写的都会原封不动放到vm里,但是computed里面的东西写的是对象,最后放到vm里的是这个对象的名,值是get里的返回值。

下面看下Vue中监视属性和计算属性区别。

需求

我们将计算属性的案例使用watch写一遍

需求一揽

使用watch实现

自实现

data:{
 // 全名
 fullname:{
    full:""
    name:""
},
userName:""
},

准备工作

html

<!-- 创建一个容器 -->
    <form class="app">
        <input type="button" value="重置" @click="reset">
        <!-- 差值语法 == v-model -->
        <div class="box" >
            <div class="title">深度监视</div>
            请输入:<input type="text" v-model="fullName.full"><br>
            请输入:<input type="text" v-model="fullName.name">
            <!-- 使用深度监视 -->
            <div class="content">{{userName}}</div>
        </div>
    </form>

js

<script>
    var vm = new Vue({
      el: '.app',
      data: {
        // 全名
        fullName:{
            full:"",
            name:""
        },
        userName:""
      },
      methods:{
        // 清除fullName的值
        reset(){
            this.fullName.full = ""
            this.fullName.name = ""
        }
      },
      // 对fullName进行监视
      watch:{
        fullName:{
            deep:true,
            handler(){ 
                this.userName = this.fullName.full + "-" + this.fullName.name
            }
        }
      }
      
    });
</script>

this.userName = this.fullName.full + "-" + this.fullName.name

测试

新需求

// 对fullName进行监视
      watch:{
        'fullName.full':{
            handler(newValue){
                // 新增一个定时器
                setTimeout(()=>{
                    this.userName = newValue + "-" + this.fullName.name
                },1000)
            }
        },
        'fullName.name':{
            handler(newValue){
                this.userName = this.fullName.full + "-" + newValue;
            }
        }
      }

注意点

测试

在computed当中书写

是不能够通过异步请求来去维护数据的

//配置计算属性
computed:{
    //完整写法
    /* fullname:{...
    // 简写形式
    /*fullName:funaction(){...
    fullName(){
      return this.full + "-" + this.name
  }
}

// 对fullName进行监视
watch:{
 fullName:{
     deep:true,
     handler(){
          this.userName = this.fullName.full + "-" +this.fullName.name
	  }
	 }
}

总结

computed与watch配置项

到此这篇关于Vue中监视属性和计算属性区别的文章就介绍到这了,更多相关vue监视属性和计算属性内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://www.cnblogs.com/wavesbright/p/16836542.html

标签:[!--infotagslink--]

您可能感兴趣的文章: