フロントエンドとして Vuejs を利用した中規模のプロジェクトに取り組んでいます。多くのコンポーネントで使用される可能性のある一般的なメソッドをカプセル化/分離するために私が検討しているオプションには、ミックスイン アプローチとプラグイン アプローチが含まれます。
Mixin アプローチ
mixin メソッドを使用する各コンポーネント (ファイル) に import ステートメントを記述する必要があります。ミックスインが複数の場所にインポートされるため、最終的なファイル サイズは増加しますか? this
mixinメソッド内で 使用できます。
プラグイン アプローチ
プラグインをグローバルにインストールしVue.use(MyPlugin)
、各コンポーネントにプラグインをインポートすることなく、任意のコンポーネントでプラグインを使用できます。
欠点:this[field]
プラグイン メソッド内で使用できません。vm
このようなメソッドを使用する には、呼び出し元コンポーネントのインスタンスを渡す必要があります。
編集 1 - Extend Approach を含めるには Extend Approach
他
の複数のコンポーネントで使用されるすべてのメソッドを含む基本コンポーネントを定義し、この BaseComponent を拡張して新しいコンポーネントを作成できます。ここでも、継承コンポーネントのインスタンスを渡す必要があります。BaseComponent で使用される this は、呼び出し/継承コンポーネントを参照しません。
私が以下で使用しているものと同様のコードの簡単な例を見つけてください。
//mixin.js
var MyMixin = {
methods:{
getName(){
return this.name;
}
}
};
export default MyMixin;
//plugin.js
var MyPlugin = {};
MyPlugin.install = function(Vue, options){
var service = {
getTheName(){
retrun this.name;
},
getTheNameVersion2(vm){ //here vm is the instance of the calling component passed as a parameter - is this proper way?
return vm.name;
}
}
Vue.prototype.$service = service;
};
export default MyPlugin;
//my-component.js
import MyMixin from './mixin';
export default{
template:require('./my-component-template.html'),
mixins:[MyMixin],
data(){
return{
name:'John Doe'
}
},
methods:{
displayNameFromMixin(){
console.log(this.getName()); //displays John Doe - using the mixin method.
},
displayNameFromPlugin(){
console.log(this.$service.getTheName()); //error "this" references the plugin instead of the component instance
},
displayNameFromPluginVersion2(){
console.log(this.$service.getTheNameVersion2(this)); //this works - passing the instance as method parameter
}
}
//base-component.js
export default{
methods:{
getName(vm){
return vm.name;
}
}
}
//another-component.js
import BaseComponent from './base-component';
BaseComponent.extend({
template:require('./another-component-template.html'),
data(){
return{
name:'Jack Daniels';
}
},
methods:{
getNameFromBaseComponent(){
console.log(this.getName(this)); //displays Jack Daniels - instance passed as method parameter
}
}
});
//main.js
import Vue from 'vue';
import MyPlugin from './plugin';
import MyComponent from './my-component';
import AnotherComponent from './another-component';
Vue.use(MyPlugin);
new Vue({
el:'body',
components:{
MyComponent, AnotherComponent
}
});
私の質問:
すべてのコンポーネント (メソッドが必要) に mixin ファイルをインポートするのは効率的な方法ですか?
複数の場所 (コンポーネント ファイル) で mixin をインポートすると、mixin ファイルのコードが繰り返し含まれ、ファイル サイズが大きくなりますか?呼び出し元コンポーネントのインスタンスを
vm = this
パラメーターとして渡す - 良い方法ですか? コンポーネント インスタンスをメソッド パラメータとして渡すと、効率の問題が発生しますか?プラグイン/BaseComponent ではなく、呼び出し/継承コンポーネント インスタンスを参照する
this (instance of the calling/inheriting component)
ように、プラグインおよび/または BaseComponent 内のメソッドにバインドする方法は?this
- パフォーマンス、DRYness、ファイルサイズに関して最も効果的なアプローチはどれですか?