The mixin in Vue is to distribute reusable functions in Vue components.

1. Methods and data are not shared among various components

Unlike vuex, where one place is modified, other places will also be modified. The scope of mixin data is inside the component being introduced.

2. The hook function in the reference component is executed after the hook function in the mixed object.

3. The method with the same name in the reference component will overwrite the method mixed into the object, and the methods with different names will be merged.

4. Case analysis

HelloWorld.vue

<template>
  <div class="hello">
    <div v-for="(item, index) in mixinData" :key="index">
      姓名:{{item.name}}, 年龄:{{item.age}}
    </div>
  </div>
</template>
<script>
import CommonMethods from '../mixin/CommonMethods.vue'
export default {
  name: 'HelloWorld',
  mixins: [CommonMethods],
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted () {
    // 1、引用组件中的钩子函数在混入对象中的钩子函数后面执行。
    this.mixinData = [
      { name: '初始化数据', age: 10 }
    ]
    // 2、引用组件中的同名方法会覆盖混入对象中的方法,不同名的会合并。
    this.mixinGetData()
  },
  methods: {
    mixinGetData () {
      this.mixinData = []
      return []
    }
  }
}
</script>

CommonMethods.vue

<script>
export default {
  name: 'mixinMethods',
  data () {
    return {
      mixinData: []
    }
  },
  mounted () {
    this.mixinData = [
      { name: '初始化数据', age: 0 }
    ]
  },
  methods: {
    mixinGetData () {
      let data = [
        { name: 'zxc', age: 32 },
        { name: 'lvy', age: 27 }
      ]
      this.mixinData = data
      return data
    }
  }
}
</script>

张旭超
1.4k 声望222 粉丝

精通 html+div+css jquery, vue, angularjs, angular2, angular4, ionic, ionic2