Thursday, September 20, 2018

Vue.js pass parameter to computed property would makes caching not works.

You may want to know can we declared a computed property with parameter, there is some method provided in stackoverflow and works.

Can I pass parameters in computed properties in Vue.Js 

However, I find it makes that computed property recalculate every time what methods property does ! Let have an example :

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<html>
<head>
    <title>Computed - Vue.js</title>
</head>
<body>
    <div id="app">
        <button v-on:click="count++">Increase</button>
        <p>Counter : {{getResult()}}</p>
        <p>Show greeting : {{greet("Hi!")}}</p>
    </div>
    <script>
new Vue({
    el:"#app",
    data:{
        count: 0
    },
    methods:{
        getResult(){
            console.log("Rendered counter result : "+this.count);
            return this.count;
        }
    },
    computed:{
        greet(){
            //return msg => {console.log("Rendered "+msg); return msg;}
            return function(msg){
                console.log("Rendered "+msg);
                return msg;
            }
        }
    }
});
    </script>
</body>
</html>
The result interface :
 This example use the stackoverflow's answer returning function with paramters in computed property. The line "Rendered Hi!" in console shown the greet() runs.


However it's not expect that greet() method recalculate each time i click the "Increase" button, it act as methods did.  If the computed properties are not cached I would more prefer keep using the methods property.

Finally, I checked the offical doc and doesn't find any sentence tell developer the way to pass parameter to computed property, hack may not always works.
https://vuejs.org/v2/guide/computed.html

3 comments :

  1. The caching is based on the dependency the computed property is working on, not the parameters.

    ReplyDelete
  2. If you really want cache of your view, use Components

    ReplyDelete