今回は、ミックスインという概念やその利用方法を紹介していきます。
Vue.jsの書き方を最初から知りたいという方はこちら(^^)
参考書
ミックスインとは
ミックスインとは、簡単にいうと機能を再利用し保守性を高めるための仕組みです。
説明の前に、まずは保守性のよくない例を見てみましょう。
以下のサンプルは税込価格を返す二つのコンポーネントになりますが、異なるのは税抜価格と税率のみです。
<div id="app">
<sample1></sample1>
<sample2></sample2>
</div>
// main.js(親コンポーネント)
var app = new Vue({
el: '#app',
components: {
'sample1': sample1,
'sample2': sample2
}
});
// sample.js(子コンポーネント)
var sample1 = {
template: `
<p>
{{notTaxedPrice}}円(税抜)
<button v-on:click="cal">税込金額({{tax * 100}}%)</button>
<span v-if="show">
{{taxedPrice}}円(税込)
</span>
</p>
`,
data: function() {
return {
notTaxedPrice: 5000,
taxedPrice: 0,
tax: 0.08,
show: false
}
},
methods: {
cal: function() {
this.taxedPrice = Math.floor(this.notTaxedPrice * ( 1 + this.tax ));
this.show = true;
}
}
};
var sample2 = {
template: `
<p>
{{notTaxedPrice}}円(税抜)
<button v-on:click="cal">税込金額({{tax * 100}}%)</button>
<span v-if="show">
{{taxedPrice}}円(税込)
</span>
</p>
`,
data: function() {
return {
notTaxedPrice: 3000,
taxedPrice: 0,
tax: 0.1,
show: false
}
},
methods: {
cal: function() {
this.taxedPrice = Math.floor(this.notTaxedPrice * ( 1 + this.tax ));
this.show = true;
}
}
};
二つのコンポーネントの構成がほとんど同じであるため重複する部分がかなりありますね。
この書き方の問題点は、同じ内容を二度も書くという手間がかかるという点もありますが、保守性もよくありません。
後にコードを修正する際に手作業で二か所変える必要が出てきます。
ここでミックスインの出番です。
大部分の共通項目を一つにまとめ使いまわすことで記述を減らし、
保守性も上げることができます。
// sample.js(子コンポーネント)
//共通部分を変数に入れる
var myMixin = {
template: `
<p>
<button v-on:click="cal">税込金額({{tax * 100}}%)</button>
{{notTaxedPrice}}円(税抜)
<span v-if="show">
→ {{taxedPrice}}円(税込)
</span>
</p>
`,
data: function() {
return {
taxedPrice: 0,
show: false
}
},
methods: {
cal: function() {
this.taxedPrice = Math.floor(this.notTaxedPrice * ( 1 + this.tax ));
this.show = true;
}
}
};
var sample1 = {
mixins: [myMixin],
data: function() {
return {
notTaxedPrice: 5000,
tax: 0.08,
}
}
};
var sample2 = {
mixins: [myMixin],
data: function() {
return {
notTaxedPrice: 3000,
tax: 0.1,
}
}
};
共通部分を変数に入れ、コンポーネントの mixins プロパティで指定します。
mixins が配列になっているのは、複数のミックスインを追加できるからですね。
ブラウザには以下のように表示されます。

今回は以上になります。
ご覧いただきありがとうございました(^^)
参考書
コメント