Home  >  Q&A  >  body text

How to use reusable code from another file in Vue 3's composition API?

<p>I created reusable code in dateTime.js: </p> <pre class="brush:php;toolbar:false;">import { ref, computed, watch } from 'vue'; import * as dayjs from 'dayjs'; export default function dateTime() { const newDateTimeString = ref(null); function showDateTime(data) { const dateTime = dayjs(data).format('DD-MM-YYYY') newDateTimeString.value = dateTime; } return { newDateTimeString, showDateTime } }</pre> <p><strong>The code in dateTime.js is called in Table.vue: </strong></p> <p>Question: How do I make it work? I want to use <code>{{ showDateTime(scope.row[itemIn.field]) }}</code> in the template. It seems to me that this should eventually trigger the <code>showDateTime</code> function in <code>dateTime.js</code>. </p> <p>What did I do wrong? Error code: <code>Uncaught (in promise) TypeError: Object(...) is not a function</code>, which refers to <code>const { showDateTime } = useDateTime();</code> ;</p> <pre class="brush:php;toolbar:false;"><template v-else-if="itemIn.type == 'dateTime'"> {{ showDateTime(scope.row[itemIn.field]) }} </template> <script> import { ref, computed } from 'vue'; import { defineComponent } from "vue"; import { useStore } from "vuex"; import { useDateTime } from '@/composables/dateTime'; export default defineComponent({ name: "", props: { processingData: Object }, components: { Flag }, emits: ["unique", "refresh"], setup(props, {emit}) { const { showDateTime } = useDateTime(); const store = useStore() function setStatus(id, route) { const object = { id: id, route: route } return store.getters.getStatus(object); } return { getScope, setUniqueId, getClass, getWidth, navigatePagination, setStatus, setTag, showDateTime }; } }); </script></pre> <p><br /></p>
P粉323050780P粉323050780392 days ago492

reply all(1)I'll reply

  • P粉964682904

    P粉9646829042023-08-27 09:54:34

    When you use the export default export useDateTime hook, you must import without using { }:

    import useDateTime from '@/composables/dateTime';

    reply
    0
  • Cancelreply