Search code examples
javascriptvue.jsvuejs2vue-componentvue-mixin

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


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


Solution

  • 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.