混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
使用示例:
需求:
假设我 demoA组件和demoB组件中有相同的一些方法和处理逻辑。这时候我们为了不写重复的代码,可以视情况使用 混入mixins.
演示目录:
在mixins.js里定义了混入对象 并通过export导出:
// 定义一个混入对象:(这里是局部混入,全局混入官网详见:https://cn.vuejs.org/v2/guide/mixins.html) //具体混入对象和组件直接的使用详见: https://cn.vuejs.org/v2/guide/mixins.html //在demoA.vue 和 demeB.vue混入以后,两个组件里就都拥有了, hello方法,并自动在created中执行 export var myMixin = { //组件中的其他属性 都可写在这里 methods: { hello: function (msg='') { console.log('hello from mixin!' + msg); } }, created: function () { this.hello(); // 同名钩子函数将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。 console.log('混入对象-created'); } };
在demoA组件和demoB组件中使用 mininx 混入。
demoA.vue
<template> <div class="demoA"> demoA </div> </template> <script> import { myMixin } from './mixins/mixins'; export default { name: 'demoA', mixins: [ myMixin ], //混入 相当把 混入对象的 属性 都 写在了当前 组件里。 data(){ return { } }, methods: { bar: function () { console.log('demoA-methods-bar'); } }, created(){ this.bar(); }, mounted () { console.log('demoA-mounted'); // this.hello(demoA); //调用混入对象中methods中的方法 -> hello from mixin!demoA } }; </script> <style scoped> </style>
demoB.vue
<template> <div class="demoB"> demoB </div> </template> <script> import { myMixin } from './mixins/mixins'; export default { name: 'demoB', mixins: [ myMixin ], //混入 相当把 混入对象的 属性 都 写在了当前 组件里。 data(){ return { foo: 'foo' } }, methods: { }, created(){ console.log('demoB-created') }, mounted () { console.log('demoB-mounted'); // this.hello('demoB'); //调用混入对象中methods中的方法 -> hello from mixin!demoB } }; </script> <style scoped> </style>
简单运行效果:
具体使用方式:详见官网api:https://cn.vuejs.org/v2/guide/mixins.html