语法:

计算属性:computed:{
                 变量名:function (){
                    ...处理
                     return 返回值;
                 }
             }

方法:

  methods:{
                 方法名:function(){
                    ...处理

                   可返回值也可以不返回
                 }
             }

监听器

watch:{
                 被监听属性:function(){
                    属性改变时处理...
                }

代码如下:想看结论直接往下拉

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue的计算属性,方法,监听器</title>
      <script src="vue.js"></script>
</head>
<body>
    <div id = 'app2'>
        <h1>{{num1}}</h1>
        <h1>{{num2}}</h1>
        <h1>{{numz}}</h1>
        <h1>{{total}}</h1>
        <h1>{{total1()}}</h1>
        <h1>{{total2}}</h1>
    </div>
    <script>
        var app = new Vue({
            el:'#app2',
            data:{
                num1:0,
                num2:0,
                numz:666,
                total2:0,
                },
            //计算属性返回值实现
             computed:{
                 total:function (){
                     
                     console.log("计算了一次1");
                     return this.num1+this.num2;s
                 }
             },
             //方法实现
             methods:{
                 total1:function(){
                     console.log("计算了一次2");
                     return this.num1 + this.num2;
                 }
             },
             //监听器实现
             watch:{
                 num2:function(){
                     console.log("计算了一次3");
                    this.total2 = this.num1+this.num2;
                },
                num1:function(){
                    console.log("计算了一次3");
                    this.total2 = this.num1+this.num2;
                }
        },
        });
    </script>
</body>


</html>

页面效果与测试如下

手把手教你VUE从入门到放弃—— 篇 八(vue的计算属性,方法和监听器的使用方法与比较)

结论:

刚加载页面的时候调用了方法与计算属性 

修改了无关变量时,因为计算属性与监听有缓存而方法没有,所以手把手教你VUE从入门到放弃—— 篇 八(vue的计算属性,方法和监听器的使用方法与比较)

修改了相关变量时,缓存重置,重新计算

由此可以看出此场景时 计算属性最好用,既简洁又有缓存

相关文章:

  • 2022-12-23
  • 2021-05-23
  • 2022-01-17
  • 2022-02-03
  • 2021-08-10
  • 2022-12-23
  • 2021-11-26
  • 2021-07-27
猜你喜欢
  • 2021-12-15
  • 2021-09-13
  • 2021-08-09
  • 2022-12-23
  • 2021-04-19
  • 2021-11-24
  • 2021-06-03
相关资源
相似解决方案