Vue advanced features mixin mixing

Mixins provide a very flexible way to distribute reusable functions in Vue components. Mixins are often used in projects to abstract common logic.

Mixin supports global mixing and local mixing. Global mixing should be used with caution because it will affect each separately created Vue instance (including third-party components)!

1. Global mix-in

Vue.mixin({
  created: function () {
    console.log("全局混入")
  }
})

2. Local mixing

import mixin1 from './mixin1'
export default {
  mixins:[mixin1]
}

Note: When the component has the same options as the mixin object, the component options will override the mixin options during recursive merging; but if the same options are life cycle hooks, they will be merged into an array and the mixin will be executed first. hook, and then execute the component's hook.

3. Sample code

To control whether the element is displayed, v-show will be used. If the variables and rules used in the two components are the same, the display of the control element can be encapsulated separately into a mixin.js file.

# mixin1.js中
export default {
  data() {
    return {
        isShowing: true
    }
  },
  methods: {
    show() { 
        this.isShowing = !this.isShowing
    }
  }
}
# modal.vue中
<template>
  <div id="app">
    <button @click="show()">modal显示与隐藏</button>
    <div v-show="isShowing">modal显示</div>
  </div>
</template>

<script>
import mixin1 from './mixin1'
export default {
  mixins: [mixin1]
}
</script>
# tooltip中
<template>
  <div id="app">
    <button @click="show()">tooltip显示与隐藏</button>
    <div v-show="isShowing">tooltip显示</div>
  </div>
</template>

<script>
import mixin1 from './mixin1'

export default {
  mixins: [mixin1]
}
</script>

End----------------------

Guess you like

Origin blog.csdn.net/u011690675/article/details/130262014