This is the 22nd day of my participation in Gwen Challenge. For details, see Gwen Challenge.
In Vue, computed attributes (computed) are derived from other reactive attributes and are used to automatically listen for changes in reactive attributes to dynamically calculate the return value. A computed attribute (computed) is usually a function with no parameters. Of course, if you need to pass parameters to a calculated property like calling a method, it is also possible. This article introduces two methods for passing parameters to a calculated property.
1. Return function
This method is passed by counting the function returned by the attribute, as shown in the following code snippet. For an unapproved record, the review time is 0, which shows — :
<template> <div id="app"> <p> <label> </label> <i class="number"> {{ auditTime(1624314956) }} </i> </p> </div> </template> <script> export default { computed: { auditTime: () => { return (timestamp) => (timestamp > 0 ? convertDate(timestamp) : "--"); ,}}}; </script>Copy the code
The calculation property auditTime of the above code returns an arrow function that accepts timestamp as a timestamp and convertDate as a timestamp time format.
2.filters
You can add a filter to the component so that you can format the values in the template the way you want.
Vue filters are defined in the official documentation as follows:
Vue.js allows you to customize filters that can be used for some common text formatting. Filters can be used in two places: double curly brace interpolation and v-bind expressions (the latter supported as of 2.1.0+). Filters should be added to the end of JavaScript expressions, indicated by the “pipe” symbol.
<template> <div id="app"> <p> <label> </label> <i class="number"> {{ 1624314956 | auditTime("--") }} </i> </p> </div> </template> <script> export default { filters: { auditTime: (timestamp, defaultValue = "--") => timestamp > 0 ? convertDate(timestamp) : defaultValue, }, }; </script>Copy the code
In the snippet above, the output when the timestamp is 0 is deja vu, similar to the pipes introduced in The Angular PIPE Introduction.
{{ 1621836603 | auditTime("--") }}
Copy the code
The code above finally reads: 2021-06-22 06:35.
{{ 0 | auditTime("--") }}
Copy the code
The code above finally appears as: –.
conclusion
For passing parameters in computed attributes, of course, you can define corresponding methods in methods. The main difference between methods is that computed can be cached, whereas methods cannot.