2

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.

0

1 Answer 1

1

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.

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

3 Comments

I did but from what I understand, I would have to add the mixin to my root instance, and by doing that I would get the same effect of loading such code in all pages which is what I am trying to avoid.
@enriqg9 just import the mixin in the code that is exclusive to the two pages or just check if you want to load the mixin at runtime (if...else) and import it dynamically
@riyaz-ali is right. You can import the mixin to one ore more instances by setting mixins:['yourMixin'] in each instance like data or methods, component or .vue file where you want it. In this case it is not in all pages. If you add the mixin globaly with Vue.mixin('yourMixinName', yourMixin); the code will be in all pages and components, this is not what you want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.