javascript - vue computed缓存问题
本文介绍了javascript - vue computed缓存问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我看官方文档上说:
computed
和methods
的区别是,computed
会基于它们的依赖进行缓存,如果数据没法改变则computed
刷新时不会重新执行,而methods
则会每次执行。
but我写的例子并不是这样(写的是官方的例子)。
html:
<div id="app">
<div>{{methodsNow()}}</div>
<div>{{computedNow}}</div>
</div>
javascript:
new Vue({
el:'#app',
data:{
},
methods:{
methodsNow:function(){
return new Date().toLocaleString();
}
},
computed:{
computedNow:function(){
return new Date().toLocaleString();
}
}
});
大家来探讨一下,我是不是哪里写错了?
解决方案
你的例子对于描述二者不同这点上,没有帮助。给你看这个例子:JSFiddle
<div id="app">
<!-- 每次点击时,显示的时间都不同 -->
<button @click="showMethod">methodsNow</button>
<!-- 每次点击时,显示的时间都相同 -->
<button @click="showComputed">computedNow</button>
</div>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods:{
methodsNow: function(){
return new Date().toLocaleString();
},
showMethod: function() {
alert(this.methodsNow());
},
showComputed: function() {
alert(this.computedNow);
}
},
computed:{
computedNow: function(){
return new Date().toLocaleString();
}
}
})
这篇关于javascript - vue computed缓存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文