Why does mounted in Vue plug or in Mixin work several times?

1.9k views Asked by At

Why does it repeat itself and how to prevent it and make it happen only once ? Is it bug? Here in plugin:

const globala = {
  install(Vue) {
    Vue.mixin({
      mounted() {
        console.log('hi')
      }
    })
  }
}

And here in just mixin:

Vue.mixin({
  mounted() {
    console.log('hi')
  }
})

enter image description here

1

There are 1 answers

0
Dan On BEST ANSWER

A mixin can either be global or local to a component. If you define it globally, it will be applied to every component created afterwards:

Vue.mixin({
  mounted() {
    console.log('hi')
  }
})

If you define it locally, it will only apply to the components where you manually add it:

const myMixin = {
  mounted() {
    console.log('hi')
  }
}

new Vue({
  el: "#app",
  mixins: [myMixin] // Only added to this component
});

You've defined a global mixin, so every component created afterwards will implement the mounted hook.