Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Vue Lifecycle Hooks

Tags:

vue.js

vuejs2

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.

like image 232
skribe Avatar asked Feb 21 '26 19:02

skribe


1 Answers

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>
like image 65
zero298 Avatar answered Feb 24 '26 05:02

zero298