vue监听数据:computed与watch/methods

您所在的位置:网站首页 vue监听变量变化 vue监听数据:computed与watch/methods

vue监听数据:computed与watch/methods

2023-12-23 18:26| 来源: 网络整理| 查看: 265

computed计算属性: 与methods的区别: 1.computed存储的是计算属性,不是函数,调用时不写括号; 2.计算属性监听指定数据,当指定数据发生改变时,才会被触发 watch侦听属性: 对象名代表要监听的数据, 对象值为数据改变时要做的操作(回调函数), 监听的数据的最新值会以形参的方式传进这个函数, 仅监听的数据更新时才触发操作

watch与computed的区别: 1.没有返回值 2.可以写异步代码 3.只监听单个变量

举例: computed与methods的区别: 所有的变量触发重新渲染时,methods里所有的方法均会被执行一遍; computed里的属性只在监听的数据发生改变触发重新渲染时,才会执行对应的操作

count+1 count-1 {{count}} {{result()}} {{output}} count2+1 {{count2}} new Vue({ el: "#app", data:{ count:0, count2:0 }, computed:{ output : function(){ console.log("output"); return this.count>5 ? "大于5":"小于5" } }, // 计算属性 methods:{ increase: function(){ this.count++; }, de:function(){ this.count--; }, result: function(){ console.log("result") return this.count>5 ? "大于5":"小于5" } } })

在这里插入图片描述

当点击第一行的两个按钮时,操作count的加减,result()和output均对count做是否大于5的判断,

第三个按钮是操作count2的,点击此按钮时,count2累加,下方数值发生改变,result()与count2无关,但也被执行,输出"result",而output则不做反应

在这里插入图片描述

如果没有显示count2的数值,即页面没有改变,只有点击"count2+1"按钮的操作,页面没有触发重新渲染,methods里的方法也不会被触发

注释掉显示count2数值的p标签:

{count2}}

-->

点击"count2+1"按钮,页面显示没有改变,result()和output均不触发: 在这里插入图片描述 computed与watch的区别:

// 不用return(大于5/小于5),监听单个变量 new Vue({ el: "#app", data:{ count:0, output2:"" }, watch:{ count:function(val){ this.output2 = val > 5 ? "大于5":"小于5" // 不用return } // 一开始output2是没有显示的 }, computed:{ output: function(){ return this.count > 5 ? "大于5":"小于5" } // 一开始就显示output } }) count+1 count-1 {{count}} {{output}} | {{output2}}

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3