Implementing Custom Filters for Data Formatting in Templates

Discover how to create and use custom filters to format data directly in your Vue templates for enhanced presentation.

0 likes
28 views

Rule Content

{
  "title": "Implementing Custom Filters for Data Formatting in Templates",
  "description": "Ensure that custom filters are utilized for data formatting directly within Vue templates to enhance presentation and maintain clean, readable code.",
  "category": "Vue Cursor Rules",
  "severity": "warning",
  "condition": {
    "pattern": "\\{\\{\\s*[^|]+\\s*\\}\\}",
    "message": "Consider using a custom filter for data formatting to improve code readability and maintainability."
  },
  "examples": [
    {
      "bad": {
        "code": "<template>\n  <p>{{ date.toLocaleDateString() }}</p>\n</template>"
      },
      "good": {
        "code": "<template>\n  <p>{{ date | formatDate }}</p>\n</template>\n\n<script>\n  Vue.filter('formatDate', function(value) {\n    if (!value) return '';\n    return new Date(value).toLocaleDateString();\n  });\n</script>"
      }
    },
    {
      "bad": {
        "code": "<template>\n  <p>{{ price.toFixed(2) }}</p>\n</template>"
      },
      "good": {
        "code": "<template>\n  <p>{{ price | currency }}</p>\n</template>\n\n<script>\n  Vue.filter('currency', function(value) {\n    if (!value) return '';\n    return '$' + parseFloat(value).toFixed(2);\n  });\n</script>"
      }
    }
  ]
}