如何在Vue 3的组合API中使用来自另一个文件的可重用代码?
P粉323050780
2023-08-26 13:01:48
<p>我在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>在Table.vue中调用了dateTime.js中的代码:</strong></p>
<p>问题:我该如何使其工作?我想在模板中使用<code>{{ showDateTime(scope.row[itemIn.field]) }}</code>。在我看来,这应该最终触发<code>dateTime.js</code>中的<code>showDateTime</code>函数。</p>
<p>我做错了什么?错误代码:<code>Uncaught (in promise) TypeError: Object(...) is not a function</code>,它指的是<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>
当你使用
export default
导出useDateTime
hook时,你必须在导入时不使用{ }
: