Make Your Vue App More Consistent with Base Components

May 10 2018 | By Taha Shashtari

Consistency is what distinguishes the good apps from the great. The user expects to see the same behavior and styling of a text input, for example, across all pages of the app. Of course, there are some cases where we need to use a slightly different version of that element in some part of the app, but still we need all elements to look and the feel the same everywhere in the app.

Vuetify is a great example of a component framework that makes the application's UI more consistent. This library is perfect when you want to use Material Design in your app. But if you're looking for something more unique, you have to build your components by yourself, or at least mix some 3rd party UI components in a unique way.

To make this possible, we have to create a custom component for each reusable element in our app, such as text inputs, buttons, dropdowns, etc.

We usually call these components "Base Components". Base components are those components that don't hold any logic about the current app state. They are simple, pure components that we reuse across the whole app to build its UI.

To distinguish between Base Components and other components, we should begin their names with a specific prefix, such as Base (for example: BaseTextInput, BaseButton, BaseIcon, etc).

Since we're going to use these components very frequently, it would be better to make them global instead of importing them every time we want to use them.

Doing so with Webpack is so easy. Just add this code to your main.js:

// Import all base components
const requireComponent = require.context('./components', true, /Base[A-Z]/)
requireComponent.keys().forEach((fileName) => {
  let baseComponentConfig = requireComponent(fileName)
  baseComponentConfig = baseComponentConfig.default || baseComponentConfig
  const baseComponentName = baseComponentConfig.name || (
    fileName
      .replace(/^.+\//, '')
      .replace(/\.\w+$/, '')
  )
  Vue.component(baseComponentName, baseComponentConfig)
})

Note that this code assumes that you're putting all of your components inside components directory.

So now, whenever you want to use a text input, you just write <base-text-input/> and you'll get the same text input that you're using elsewhere in the app. Not only that, but also when you want to modify the element, you just need to change the related base component once, and everything will update accordingly.