I've been trying to wrap my head around best practices in vue.js ( pinia as store). I'm coming from using Django templates where one can use template functions on variables to massage data for displaying. However, I'm not sure where to put such functions in vue.js.
Suppose I have a variable holding a string and I want to cut off trailing digits. The variable is coming from a vue.js for-loop over a list variable present in the store. I would create some function to do so:
displayString(s) {
const re = /\d $/;
return s.replace(re, "");
}
I would use it in the template in some way:
<th v-for="(item, index) in store.myList" :key="index">
{{ displayString(item) }}
</th>
To me, neither place for putting the function (methods
/computed
or actions
/getters
in pinia) would be right as they are all intended to use data from the store or component (and not all of them accept parameters anyway).
Conceptually, where would a function go that does not return data from the component or store but accepts a parameter and returns a modified version of it? Or should I design things differently, writing getters
/computed
functions that massage the list in some way for displaying the data?
I assume there are (hacky?) ways to achieve what I want (e.g. getters
/computed
returning a function I can pass the parameter to), but I want to know the best way to handle this in general.
CodePudding user response:
This kind of helper function is known as a filter in Vue 2, and it could be used like:
{{ item | displayString }}
Filters were removed in Vue 3, now functions are supposed to be used directly in a template like:
{{ displayString(item) }}
This function is general-purpose formatter that is not specific to a store and doesn't use its state, so it doesn't belong to Pinia. Instead, displayString
can be imported in a component where needed. Or be registered globally:
app.config.globalProperties.displayString = displayString