Vue组件中showDate方法类型为undefined报错的解决咨询
Looks like the issue boils down to how you're exporting the showDate function in your utility file—right now, the function isn't properly exposed for your component to import, which leaves the method undefined. Here's how to fix it step by step:
Step 1: Correct the Export in changeFormatDate.js
You’ve defined the function but haven’t exported it, so your component can’t access it. Update the utility file to use a named export:
// changeFormatDate.js import moment from 'moment'; // Add this import to keep the utility self-contained export const showDate = function (d) { return moment(d).format("DD/MM/YYYY"); };
Note: Install moment via npm/yarn if you haven’t already, and import it directly in the utility file—this avoids relying on the component’s import and keeps the function independent.
Step 2: Confirm Component Setup
Your component code is nearly correct, but double-check the import path matches your project structure. Once the export is fixed, the existing method assignment will work. Here’s the verified working version:
<template lang="pug"> .data(v-for="(rata,index) in loan.schedule" :key="index") .values span {{index+1}} span {{showDate(rata.date)}} </template> <script> import { showDate } from "@/util/changeFormatDate.js"; import moment from "moment"; export default { name: "TimetableApplication", props: { loan: { type: Object, required: true } }, methods: { showDate // Shorthand syntax for `showDate: showDate` } }; </script>
Why This Resolves the Error
- The named export (
export const showDate) makes the function available to import using the curly brace syntaximport { showDate } from .... - Adding the function to the component’s
methodsobject lets Vue access it in the template, eliminating the "undefined method" error.
Optional: Use a Filter for Reusability
If you need this date formatter across multiple components, consider registering it as a local filter for cleaner template code:
// In your component's script section filters: { showDate: showDate }
Then use it in the template like this:
span {{ rata.date | showDate }}
内容的提问来源于stack exchange,提问作者anna

