mixins easy to use

Mixins are a very flexible way to distribute reusable functions in Vue components. A blend object can contain any component option. When a component uses a mixed object, all the options of the mixed object are mixed into the options of the component itself.
Here I use a small demo to implement the function:

Directory structure:

The outermost index.vue

<template>
  <div class="MininsMin">
    <div style="color:red">{{message}}---{{foo}}---{{name}}</div>
    <div style="color:green">{{addString}}</div>
  </div>
</template>
<script>
// 1 - all the options of the mixed object will be mixed into the options of the component itself;
// 2-hook functions with the same name will be mixed into an array, so they will all be called. In addition, the hook of the object will be called before the hook of the component itself.
// 3-methods, components, and directives, will be mixed into the same object. When two object key names conflict, the key value pairs of component objects are taken.
import mixin from './data/index'
export default {
  mixins: [mixin],
  name: 'MininsMin',
  data: function () {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created: function () {
    console.log(this.$data)
    console.log('Component hook called')
  },
  computed: {
    addString () {
      return `${this.name} and ${this.age}`
    }
  }
}
</script>
<style lang="less" scope>
</style>

index.vue in it

<script>
import one from './one'
import two from './two'
var mixin = {
  ...one,
  ...two
}
export default mixin
</script>

one.vue in it

<script>
var one = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc',
      name: 'Ma you Chen'
    }
  },
  created: function () {
    console.log('one Hook of mixed object is called')
  }
}

export default one
</script>

two.vue inside

<script>
var two = {
  data: function () {
    return {
      name: 'Xiao you Chen',
      age: 108,
      foo: 'efg',
      sex: 'man'
    }
  },
  created: function () {
    console.log('two Hook of mixed object is called')
  }
}

export default two
</script>

The renderings are as follows:

Keywords: Vue less

Added by jossejf on Mon, 11 Nov 2019 22:41:38 +0200