I want to load all components in a specific directory and display it in a single page using Nuxt.
Something like this,
<template>
<component :is="view" v-for"view in extensions" :key="view" />
<template>
<script>
const fs = require("fs");
Array.prototype.last = function () {
return this[this.length - 1];
};
const sfc = fs
.readdirSync("monitors")
.filter((filename) => filename.split(".").last() == "vue")
</script>
<script setup>
import { ref } from "vue";
const extensions = ref(sfc);
</script>
I cant find any way to make it possible, I'm thinking it's impossible or I'm missing something important.
It's not a good idea to read the file as text with fs
. fs
is a nodejs module and it won't work in client side. Not to mention you will have a hard time actually instanciating your components this way.
You can just use a glob import for the directory:
<template>
<component :is="view" v-for"view in extensions" :key="view" />
</template>
<script setup>
import * as extensions from '@/components/extensions'
</script>
You just need to create an index
file in your directory and export all your components. This is sadly a required manual step, this file won't update itself when you add a new component.
|- extensions
\_ index.js
\_ Extension1.vue
\_ Extension2.vue
// index.js
export { default as Extension1 } from './Extension1.vue'
export { default as Extension2 } from './Extension2.vue'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.