0%

【029】Vue选项:computed 和 methods 的区别

调用方式

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<div>methodsMsg = {{ methodsMsg() }}</div>
<div>computedMsg = {{ computedMsg }}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data() {
return {
msg: '我是信息'
}
},
computed: {
computedMsg() {
return this.msg;
}
},
methods: {
methodsMsg() {
return this.msg;
}
}
})
</script>
</body>
</html>

通过上面的代码可以发现,computed 定义的方法是以属性访问的形式调用的,methods 定义的方法是以函数调用的形式调用的。

computed 的缓存功能

上一章有提到过,computed 是支持缓存的,这要怎么证明它是支持缓存的呢?先来看一下下面的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app">
<div>computedMsg = {{ computedMsg }}</div>
<div>computedMsg = {{ computedMsg }}</div>
<div>computedMsg = {{ computedMsg }}</div>
<div>methodsMsg = {{ methodsMsg() }}</div>
<div>methodsMsg = {{ methodsMsg() }}</div>
<div>methodsMsg = {{ methodsMsg() }}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data() {
return {
msg: '我是信息'
}
},
computed: {
computedMsg() {
alert('computedMsg');
return this.msg;
}
},
methods: {
methodsMsg() {
alert('methodsMsg');
return this.msg;
}
}
})
</script>
</body>
</html>

在浏览器中运行上面的代码,我们可以看到:computedMsg出现了一次弹出框,而methodsMsg出现了三次弹出框。

发现:
1,computed 定义的 computedMsg 方法只会做一次计算,返回一个值;
2, methods 定义的 methodsMsg 方法只要是遇见methodsMsg()都会运行。

结论:
computed 更适合复杂逻辑,避免重复调用造成的浪费,从而提高性能,优化用户体验。

总结

1,computed 是属性调用,而 methods 是函数调用;
2,computed 带有缓存功能,而 methods 没有;
3,computed 依赖于data中的数据,只有在它的相关依赖数据发生改变时才会重新求值,而 methods 需要我们调用方法时才会执行;
4,computed 也可以防止文本插值中逻辑过重而导致不易维护的情况出现。