vue computed caching issue - Stack Overflow
三叔
三叔 2017-06-12 09:31:36
0
2
964

I read the official document says:

The difference between

computed 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?

三叔
三叔

reply all(2)
三叔

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();
    }
  }
})
扔个三星炸死你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template