vue:混入(mixin)

109 阅读1分钟

基础

混入(mixin)提供了一种非常灵活的方式,分发vue组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项被混合进入该组件本身的选项。参考vue官网

示例
export const mixin = {
    data: function () {
        return {
            msg: 'hello',
            name: 'lihua'
        }
    },
    created: function () {
        console.log('hello from lihua')
    }
}

选项合并规则

  • 数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先
  • 同名钩子函数将合并为一个数组,都被调用。混入对象的钩子函数将在组件自身钩子之前调用
  • 值为对象的选项,例如methodscomponentsdirectives,将会被合并为同一个对象,两个键名起冲突时,取组件对象的键值对。

局部混入

用法:

import {mixin} from './mixin.js'

export default{
	mixins: [mixin],
	data: function(){
		msg: 'goodbye',
		bar: 'def'
	},
	created: function(){
		console.log(this.$data)
	}
}

全局混入

用法:

import mixin from '../path/mixin.js'
Vue.mixin(mixin)

全局混入会影响每一个之后创建的vue实例

自定义选项合并策略

待补充。。。

使用mixin做UI组件库

项目目录:

image.png

Button.vue

<template>
  <button :class="['lc-btn', btnStyle]">
    <slot></slot>
  </button>
</template>

<script>
export default {
  name: 'lcButton',
  props: {
    btnStyle: {
      type: String,
      default: ''
    }
  }
}
</script>

<style scoped>
.lc-btn {
  height: 34px;
  padding: 0 15px;
  border: none;
  outline: none;
  color: #fff;
  background-color: #000;
  cursor: pointer;
}
.lc-btn.btn-primary {
  background-color: #00f;
}
.lc-btn.btn-danger {
  background-color: #f00;
}
.lc-btn.btn-warning {
  background-color: orange;
}
</style>

lcUI/index.js

import lcButton from './Button';

export default {
  components: {
    lcButton
  }
}

main.js

import Vue from 'vue'
import App from './App.vue'
import lcUI from '@/libs/lcUI'
Vue.mixin(lcUI)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <lc-button>Button</lc-button>
    <lc-button btnStyle="btn-primary">Button</lc-button>
    <lc-button btnStyle="btn-warning">Button</lc-button>
  </div>
</template>

<script>

export default {
  name: 'App'
}
</script>

<style>
</style>

参考链接:你知道怎么用Vue的mixin混入做UI组件库吗?