Skip to content
Advertisement

How to share some code among components in Vue

I have component with code like that:

  export default {
    name: 'signup',
    data () {
      var myValidator = (rule, value, callback) => {
        // cut some code, but here the access to component property
        t = this.response
      };
      return {
        signupDTO: {
          email: '',
          password: '',
        },
        response: {},
        rules: {
          password: [
            {validator: myValidator},
          ],
        },
      }
    },
    methods: {

I would like to share myValidator and response in order to doesn’t repeat that code in many components. But, probably, because of lack of knowledge in Javascript I have not idea how to do that. So any advice will be appreicate.

Advertisement

Answer

Vue.js is incredibly flexible. There are multiple options available. To share data:

  1. Using Root Vue component: This component is accessible inside each component via $root property. You can use that to share the data. (Not recommended)
  2. Using Event Bus approach: Every Vue component acts like an Event Bus having $on and $emit methods. You can use that to share the data. (Ok for smaller apps and proof of concepts)
  3. Using a state management like Vuex or Redux: The most versatile and scalable way to share data across views and components. I have used both and they are both good. Vuex is simple, to begin with.

As far as sharing functionality is concerned. You can use:

  1. Mixins: Mixins allows you to share reusable pieces of code across the component. (the Recommended way)
  2. Plugins: Plugins are another way which enables you to inject and functions across all the components. This is how Vue Router or Vuex injects data/functions. Typically, you would use Vue instance or prototype patching to inject required functionality. (only recommended for advanced scenarios).
  3. Provide/Inject: You can use Vue.js dependency inject to share data/functions across parent-child components. (again recommended for advanced scenarios)
  4. Inheritance: You can also use inheritance in Vue.js. Use extends property. But beware, inheritance poses more problems than solutions.

For functions, try to rely on ES modules as much as you can to share. If you need to access Vue component instance properties inside functions, consider passing them as arguments to the function.


In a nutshell:

  1. For sharing data: Use state management like Vuex
  2. For Sharing functions: Use ES Modules or Mixins
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement