失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Vue中methods computed和watch属性联系及区别

Vue中methods computed和watch属性联系及区别

时间:2023-05-26 17:46:08

相关推荐

Vue中methods computed和watch属性联系及区别

methods属性

当我们在Vue中想要调用函数或者方法时,可以在methods中调用方法,如下:

<template><div><h1>methods属性</h1>{{ getFullname() }}{{ getFullname() }}{{ getFullname() }}{{ getFullname() }}</div></template><script>export default {name: "Methods",data() {return {firstname:'三',lastname:'张'};},methods: {getFullname:function() {console.log('1') // 4个1return this.lastname + this.firstname}}};</script>

执行上述过程可以在浏览器页面中显示四次‘张三’,由于methods没有缓存,所以控制台打印出4个1。同时,method中 getFullname是方法名,调用时需要在后面加括号。

computed属性

对于上述methods方法,如果出现大量的同一函数重复调用,会消耗大量计算资源,此时我们需要利用computed属性,如下:

<template><div><h1>computed属性</h1>{{ getFullname }}{{ getFullname }}{{ getFullname }}{{ getFullname }}{{ getFullname }}</div></template><script>export default {name: "Methods",data() {return {firstname:'四',lastname:'李'};},computed: {getFullname:function() {console.log('1') // 1个1,因为有缓存return this.lastname + this.firstname}}};</script>

执行上述过程可以在浏览器页面中同样显示四次‘李四’,但computed有缓存,上述过程是同一函数调用了多次,所以控制台只打印出1个1。同时,computed中 getFullname是一种属性,调用时无需添加括号即可执行。

补充:

其实,每个计算属性都包含一个get和一个set属性。对于上述过程,我们只是使用了get来读取,当然不指定的话默认也是get。在某些情况下,也会用到set方法(不常用,了解即可)。

<template><div><h1>computed属性</h1>{{ getFullname }}{{ getFullname }}{{ getFullname }}{{ getFullname }}{{ getFullname }}</div></template><script>export default {name: "Methods",data() {return {firstname:'四',lastname:'李'};},computed: {getFullname:{set:function(newValue){console.log(newValue)},get:function(){return this.lastname + this.firstname // 默认调用}}}};</script>

当我们对组件中的getFullname进行重新赋值后,会调用set属性,当然一般不是很常用。

watch属性

watch属性用来监听绑定数据内容变化,如下:

<template><div class=''><h1>watch属性</h1><input type="text" v-model='content'></div></template><script>export default {name: '',data(){return {content:'123'}},watch:{content:function(newValue,oldValue){console.log('oldValue:' + oldValue)console.log('newValue:' + newValue)}}}</script>

输入框内容和data中的content绑定,当输入框内容发生变化时,就会调用watch属性。

注意:watch使用时,属性名字与数据名字需一致(如上述代码中的content)。

如果觉得《Vue中methods computed和watch属性联系及区别》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。