Home > Back-end >  making reusable logic from data function in vue components
making reusable logic from data function in vue components

Time:10-02

In my application, there is a menu page component. In this component, there are multiple static data and variable initialized. Like below

data() {
  return {
    tableInfo: {
      headers: ...,
      contents: ...,
      pagination: ....
    },
    url: {
      searchUri: ...,
      detailsUri: ....
     // other component specific  uri
    },
    searhInfo: {
     label: ...,
     searchtext: ...,
    // other things
    }
  }
},

So, kind of structure is following in all other components as well and other component specific variables and data are there too.

I want to reuse this properties to all my other components as well.

I created one mixin for this and it is working correct. Is there any better approach instead of mixin?

CodePudding user response:

You said you have tried mixins and it is working correctly and I myself personally think that they are a good choice since the Vue framework recommends it

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options. -Vue Framework Definition

What you are trying to do is the same meaning making a file to reuse the functionality in components.

The approach you are using is correct and accurate to use in your situation and it is recommended by vue itself so it is not a bad practice.

no need to change it !

CodePudding user response:

You mentioned you have multiple static fields but have not mentioned anything about the dynamic contents. If you are using dynamic content then I suggest using props instead of mixins ( or a combination of both which suits your requirement).

But as of now, mixins is perfect for the current requirement.

  • Related