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>The result interface :
<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>
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
The caching is based on the dependency the computed property is working on, not the parameters.
ReplyDeleteIf you really want cache of your view, use Components
ReplyDeleteThanks for your sharing :)
ReplyDelete