enriqg9
enriqg9

Reputation: 1507

Extending root vue instance

I have a root Vue 2 instance mounted on every page of my application, and I need to add methods that will be accessed only on two pages of my app. I know I could add those methods in my root Vue instance but I'm not sure if it is the right way to go as those methods will be available from all other pages in the app and they have dependencies that I don't want to import on all pages.

// app.js

//## Root Vue Instance
window.App = new Vue({
  el: '#app',
  methods: {
    ...
  }
})

I thought about extending the global Vue prototype on a separate JS file that loads only on the page I need these methods:

// page1.js

Vue.prototype.method1 = function(){...}

However on the second page I need to access those methods I will have to repeat myself.

// page2.js

Vue.prototype.method1 = function(){...}

What is the recommended approach on this? Maybe there is a use-case for Vue mixins or plugins.

Upvotes: 2

Views: 3850

Answers (1)

reinerBa
reinerBa

Reputation: 1660

Please look at the documentation https://v2.vuejs.org/v2/guide/mixins.html#

You can use mixins to extend choosen components or instances. Also it is possible to declare a mixin global for all components and instances with one line. Mixins can do everything that an instance can do, because they truly extend them.

Upvotes: 1

Related Questions