I read the official document says:
The difference betweencomputed
and methods
is that computed
will be cached based on their dependencies. If the data cannot be changed, computed
It will not be re-executed when refreshing, but methods
will be executed every time.
But the examples I wrote are not like this (the examples I wrote are official examples).
html:
<p id="app">
<p>{{methodsNow()}}</p>
<p>{{computedNow}}</p>
</p>
javascript:
new Vue({
el:'#app',
data:{
},
methods:{
methodsNow:function(){
return new Date().toLocaleString();
}
},
computed:{
computedNow:function(){
return new Date().toLocaleString();
}
}
});
Let’s discuss, did I write something wrong somewhere?
三叔2017-06-12 09:33:36
Your example is not helpful in describing the difference between the two. Show you this example: JSFiddle
<p id="app">
<!-- 每次点击时,显示的时间都不同 -->
<button @click="showMethod">methodsNow</button>
<!-- 每次点击时,显示的时间都相同 -->
<button @click="showComputed">computedNow</button>
</p>
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();
}
}
})
扔个三星炸死你2017-06-12 09:33:36
You will understand after testing it like this
html:
<p id="app">
<p>{{methodsNow()}}</p>
<p>{{computedNow}}</p>
<p>{{methodsNow()}}</p>
<p>{{computedNow}}</p>
</p>
javascript:
new Vue({
el:'#app',
data () {
return {
mData: 1,
cData: 2
}
},
methods: {
methodsNow: function () {
console.log('methods')
return this.mData
}
},
computed: {
computedNow: function () {
console.log('computed')
return this.cData
}
}
});
As a result, you find that computedNow is executed once and methodsNow is executed twice