0

I have multiple VUE components in my Laravel project and many of them have the same method declared in them.

Is there a best practice for how to handle this? Or more importantly, is it possible to have these methods declared in one place and referenced by each component.

Toy Example

Apple Component

// ...

data() {
    return {
        page_name = 'apple'
    }
},
methods: {
    sayPage(page_name) {
        alert(`you are on the ${page_name} page`);
    }

},
mounted: {
    this.sayPage(this.page_name)
}
// ...

Banana Component

// ...

data() {
    return {
        page_name = 'banana'
    }
},
methods: {
    sayPage(page_name) {
        alert(`you are on the ${page_name} page`);
    }

},
mounted: {
    this.sayPage(this.page_name)
}
// ...

Ideally, I would like to have something like;

Shared Methods


// some file where methods can be declared once
methods: {
    sayPage(page_name) {
        alert(`you are on the ${page_name} page`);
    }

},

Apple Component

// ...

data() {
    return {
        page_name = 'apple'
    }
},
mounted: {
    SHARED_METHODS.sayPage(this.page_name)
}
// ...

Banana Component

// ...

data() {
    return {
        page_name = 'banana'
    }
},
mounted: {
    SHARED_METHODS.sayPage(this.page_name)
}
// ...

1 Answer 1

1

if you are using Vue v2 You probably need use Mixins:

What's is mixing:

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.

Example:

// define a mixin object
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})

var component = new Component() // => "hello from mixin!"

for more: https://v2.vuejs.org/v2/guide/mixins.html?redirect=true

if You are using Vue v3 probably need use: "Options: Composition"

In Vue 2, mixins were the primary mechanism for creating reusable chunks of component logic. While mixins continue to be supported in Vue 3, Composition API is now the preferred approach for code reuse between components.

for more: https://vuejs.org/api/options-composition.html

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.