I have a reusable button and I want to render it as a separate component @/components/UI/MyButton'. This element i register in 'UI/index.js'
import MyButton from "@/components/UI/MyButton";
export default {
MyButton,
};
and then I globally register through the method аorEach in 'main.js'.
import { createApp } from "vue";
import App from "./App";
import componentsUI from "./components/UI";
const app = createApp(App);
componentsUI.forEach((component) => {
app.component(component.name, component);
});
app.mount("#app");
but method forEach causes an error "components_UI__WEBPACK_IMPORTED_MODULE_2_.default.forEach is not a function", and the project is not rendered. If I do not use this method, then the button is rendered but without styles.
How can I globally register a reusable component?
CodePudding user response:
In UI/index.js
try to export an array []
not an object {}
:
import MyButton from "@/components/UI/MyButton";
export default [
MyButton,
];
CodePudding user response:
Try this:
In the components directory create the base folder then create _index.js.
// components/base/_index.js
const requireComponent = require.context(
// The relative path of the components folder
'./',
// Whether or not to look in subfolders
false,
// The regular expression used to match base component filenames
/[A-Z]\w Base\.vue$/
);
const register = (app) => {
requireComponent.keys().forEach((fileName) => {
const componentConfig = requireComponent(fileName);
const componentName = fileName
.split('/')
.pop()
?.replace(/\.\w $/, '');
app.component(componentName, componentConfig.default || componentConfig);
});
};
export default {
register,
};
The name of the Button component must be like this(based on regex): ButtonBase.vue
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import BaseComponents from './components/base/_index';
const app = createApp(App);
BaseComponents.register(app);
app.mount('#app');