Trivo
Trivo

Reputation: 123

Vue multiple components in one package/file

let's say i want to create a UI Package, how can I put multiple components into one single JS file?

Normally I would have my different components in different files:

import ButtonText from '../ButtonText.vue'
import ButtonIcon from '../ButtonIcon .vue'
import ButtonLayout from '../ButtonLayout.vue'

but I want to put all my Button components in a single file, for reuseability etc. so i can import things when I need them

import {ButtonText, ButtonIcon, ButtonLayout } from '../ButtonPackage.vue'

how would my ButtonPackage.vue/.js File look like?

Upvotes: 3

Views: 1344

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28434

The key is to export all components in one file:

import ButtonText from "./ButtonText";
import ButtonIcon from "./ButtonIcon";
import ButtonLayout from "./ButtonLayout";
export { ButtonText, ButtonIcon, ButtonLayout };

So when you want to use any of them:

import {
  ButtonText,
  ButtonIcon,
  ButtonLayout,
} from "./components/ButtonPackage";

Here is a demo I created:

https://codesandbox.io/s/crazy-oskar-gper1?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 2

Igor Moraru
Igor Moraru

Reputation: 7739

In ButtonPackage.js file you import all components, and export them as an object.

import ButtonText from '../ButtonText.vue'
import ButtonIcon from '../ButtonIcon .vue'
import ButtonLayout from '../ButtonLayout.vue'

export {ButtonText, ButtonIcon, ButtonLayout }

Then in a component you import them as needed:

import { ButtonText } from '../ButtonPackage.js'

Upvotes: 3

Related Questions