vue.jsvuejs3vue-component

Allow Users to Override Default Values in a Vue 3 Component Library


I'm developing a Vue 3 component library and want to allow users to override default values for components. Here's how users would install the library:

// Import styles and library
import { mountLibrary } from '@my/components-library'
import '@my/components-library/style.css'

const componentLibrary = mountLibrary({
  /* Add your configuration here */
})

createApp(App).use(componentLibrary).mount('#app')

I want users to be able to override the default values for a component like this:

const componentLibrary = mountLibrary({
  defaultValues: {
    toastNotification: {
      position: "bottom-right"
    }
  }
})

createApp(App).use(componentLibrary).mount('#app')

Currently, I define my props using the Composition API like this:

const props = withDefaults(defineProps<ToastNotificationProps>(), {
  position: 'bottom-right'
  // ...
})

How can I implement a feature that allows users to override these default values when they configure the component library? What changes do I need to make to support this functionality?


Solution

  • This requires to compute prop values instead of relying on default values in prop definitions. It could be seen the other way, global options could be overridden with props.

    The library plugin would provide global options:

    const createMyPlugin = ({ defaultOptions } = {}) => (app) => {
      const globalOptions = deepMerge({ toastNotification: ... }, defaultOptions);
      app.provide('my-library-options', globalOptions);
    }
    

    And it's more efficient to compute options separately for each prop:

    const props = defineProps<ToastNotificationProps>();
    const globalOptions = inject('my-library-options');
    const position = computed(() => props.position ?? globalOptions.toastNotification.position);