3

I have a special application where I would like to run a method on every component when it is mounted. So I could have the method as a global mixin or something and then simply do..

mounted(){
   this.mySpecialMethod();
}

However, I was wondering if it is possible to simply extend Vues mounted hook so the method is always run on every component when it is mounted. I have not been able to find in info on this.

4
  • yep, fork vuejs and do your work on this, but... why not mixin you have mentioned? Commented Jun 15, 2018 at 14:28
  • @mklimek "Why not mixin..." only because rather than having to add the function in every component's mounted() it would be quite cool to have it just happen on every component when it mounts. This way it would also work if anyone else adds components but does not use the mixin function. But certainly I will use the mixin if there is not other simple way. Commented Jun 15, 2018 at 14:33
  • alternatively, instead of using a mixin you can create a component that has the method, and every component can extend that class instead of the generic vue. Commented Jun 15, 2018 at 14:48
  • @skribe seems to be a cool idea until you have one which wouldn't need it ;) Commented Jun 15, 2018 at 15:11

1 Answer 1

4

If you really want to have everything call your mounted hook, you can use a global mixin.

Below, we have the mixin myMixin that will log to console every time something is mounted or destroyed. When you run the example, you can see that every time the plus button is clicked, it runs both the component's mounted hook as well as the mixin's hook.

If you want to extend this so that it can be reusable as a library, you can create a plugin out of it.

const foo = {
  template: "<div @click='onClick'>hello</div>",
  mounted() {
    console.log("Foo's mounted");
  },
  methods: {
    onClick() {
      console.log("click");
    }
  }
}

const myMixin = {
  mounted() {
    console.log("I've been mounted");
  },
  destroyed() {
    console.log("I've been destroyed");
  }
};

Vue.mixin(myMixin);

const app = new Vue({
  el: "#app",
  data() {
    return {
      foos: []
    };
  },
  components: {
    foo
  },
  methods: {
    add() {
      this.foos.push("fizz");
    },
    remove() {
      this.foos.pop();
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <button @click="add()">+</button><button @click="remove()">-</button>
  <ul>
    <li v-for="f in foos">
      <foo></foo>
  </ul>
</div>

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

1 Comment

Awesome! I have used mixins for many things but never used lifecycle hooks in them. Works perfectly for my purposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.