默认式混合
对于组件data
数据,components
组件,events
事件以及其它自定义方法采用默认式混合,即如果组件未声明该数据,组件,事件,自定义方法等,那么将混合对象中的选项将注入组件之中。对于组件已声明的选项将不受影响。
// mixins/test.js import wepy from ‘wepy‘; export default class TestMixin extends wepy.mixin { data = { foo: ‘foo defined by page‘, bar: ‘bar defined by testMix‘ }; methods = { tap () { console.log(‘mix tap‘); } } }
// pages/index.wpy import wepy from ‘wepy‘; import TestMixin from ‘./mixins/test‘; export default class Index extends wepy.page { data = { foo: ‘foo defined by index‘ }; mixins = [TestMixin ]; onShow() { console.log(this.foo); // foo defined by index console.log(this.bar); // bar defined by testMix } }
兼容式混合
对于组件methods
响应事件,以及小程序页面事件将采用兼容式混合,即先响应组件本身响应事件,然后再响应混合对象中响应事件。
注意,这里事件的执行顺序跟Vue中相反,Vue中是先执行mixin中的函数, 再执行组件本身的函数。
// mixins/test.js import wepy from ‘wepy‘; export default class TestMixin extends wepy.mixin { methods = { tap () { console.log(‘mixin tap‘); } }; onShow() { console.log(‘mixin onshow‘); } }
// pages/index.wpy import wepy from ‘wepy‘; import TestMixin from ‘./mixins/test‘; export default class Index extends wepy.page { mixins = [TestMixin]; methods = { tap () { console.log(‘index tap‘); } }; onShow() { console.log(‘index onshow‘); } }
// index onshow
// mixin onshow
// ----- when tap
// index tap
// mixin tap