vuex-pathifyでVuexBeastを飼いならす
Fluxアーキテクチャの実装に関する限り、Vue.jsのVuexは最も単純ですが、最もエレガントなものの1つです。 ただし、それでもなお良い可能性があります。 ストア内のすべてのプロパティに対してゲッターとミューテーションを作成することを忘れないようにしようとすると、少し不必要な認知的オーバーヘッドのように見えます。 また、ゲッター、ミューテーション、アクションを手動でマッピングする必要があるのはなぜですか? commit
とdispatch
の違いは何でしたか? vuex-pathify
by Dave Stewart は、Vuex機能用の単純なラッパーを提供し、慣例に依存して定型文を減らすことにより、この精神的なオーバーヘッドをすべて削減しようとします。
この記事は、VuexがすでにセットアップされているVue.jsプロジェクトがあり、それがどのように機能するかの基本を知っていることを前提としています。 そうでない場合は、Vuexガイドをご覧ください。
vuex-pathifyをインストールします
まず最初に、pathifyをインストールして、ベースのVuexストア構成でプラグインとして有効にします。
$ npm install --save vuex-pathify
次に、ストアでプラグインを有効にします。
import Vue from 'vue';
import Vuex from 'vuex';
// If you want to configure pathify, this import will be different.
// See the "Configuring Pathify" section below.
import pathify from 'vuex-pathify';
import App from './App.vue';
Vue.use(Vuex);
// Usual Vuex stuff. Normally not in the main file.
const state = {};
const getters = {};
const mutations = {};
const actions = {};
const actions = {};
const store = new Vuex.Store({
// Enable the vuex-pathify plugin.
plugins: [pathify.plugin],
state,
getters,
mutations,
actions,
modules,
});
new Vue({
store,
render: h => h(App)
}).$mount('#app');
比較
では、今の質問は…vuex-pathify
は何をするのでしょうか?
通常のvuex
これを説明するために、基本的なVuexセットアップを見てみましょう。 双方向のデータバインディングを使用して、名前と名前を編集できる小さなフォームです。
import Vue from 'vue';
import Vuex from 'vuex';
import App from './App.vue';
Vue.use(Vuex);
const state = {
firstName: 'Richard',
lastName: 'Gator'
};
// We need these to be able to access
// their values outside of the store module.
const getters = {
firstName: state => state.firstName,
lastName: state => state.lastName
};
// We use these to update the values of the store.
const mutations = {
SET_FIRST_NAME: (state, firstName) => {
state.firstName = firstName
},
SET_LAST_NAME: (state, lastName) => {
state.lastName = lastName
}
};
const store = new Vuex.Store({
state,
getters,
mutations
});
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount('#app');
<template>
<div id="app">
<h2>Your Name Is: {{firstName}} {{lastName}}</h2>
<form>
<label>
First Name
<input type="text" v-model="firstName"/>
</label>
<label>
Last Name
<input type="text" v-model="lastName"/>
</label>
</form>
</div>
</template>
<script>
export default {
name: 'app',
computed: {
// We have to create computed getters and setters for both properties
// to be able to use them in v-model.
// Quite a pain for larger forms, wouldn't you say?
firstName: {
get() { return this.$store.getters.firstName },
set(val) { this.$store.commit('SET_FIRST_NAME', val) }
},
lastName: {
get() { return this.$store.getters.lastName },
set(val) { this.$store.commit('SET_LAST_NAME', val) }
}
}
}
</script>
それは…とても単純なことのための多くの定型文です。 状態を作成し、ゲッター、ミューテーション、および計算されたプロパティを追加して、それらをすべて結び付ける必要があります。
vuex-pathifyを使用
vuex-pathify
でも同じことを見てみましょう。
import Vue from 'vue';
import Vuex from 'vuex';
import pathify from 'vuex-pathify';
import { make } from 'vuex-pathify';
import App from './App.vue';
Vue.use(Vuex);
const state = {
firstName: 'Richard',
lastName: 'Gator'
};
// You don't even need getters, pathify will use the store data directly!
// Though if you want, it can generate them for you with `make.getters(state)`
// Same for mutations and actions. (Uses the SET_* format, but this is configurable.)
const mutations = make.mutations(state);
const store = new Vuex.Store({
// Don't forget the plugin!
plugins: [pathify.plugin],
state,
mutations
});
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount('#app');
<template>
<div id="app">
<h2>Your Name Is: {{firstName}} {{lastName}}</h2>
<form>
<label>
First Name
<input type="text" v-model="firstName"/>
</label>
<label>
Last Name
<input type="text" v-model="lastName"/>
</label>
</form>
</div>
</template>
<script>
import { sync } from 'vuex-pathify';
export default {
name: 'app',
computed: {
// The sync helper creates two-way bindings for store data and mutations.
firstName: sync('firstName'),
lastName: sync('lastName'),
// We could reduce boilerplate even further using:
// ...sync(['firstName', 'lastName'])
}
}
</script>
私には冗長なコードが大幅に削減されたように見えます!
力学
vuex-pathify
の中心には、パスシステムと解決アルゴリズムがあります。 パスは次のようになります:module/[email protected]
たとえば、次のパスを使用すると、data/user/firstName
、pathifyは次のことを判別できます。
- 参照されるモジュールは、
data
モジュールのuser
サブモジュールです。 - ゲッターは
data/user/firstName
用である必要があります。 - 関連する突然変異は
data/user/SET_FIRST_NAME
です。 - 関連するアクションは
data/user/setFirstName
です。
pathify.get('data/user/firstName')
の場合、pathifyは最初にdata
モジュールのuser
サブモジュールでfirstName
であるゲッターを探します。 これに失敗すると、ストアのdata.user.firstName
プロパティを直接参照します。
pathify.set('data/user/firstName', 'Richard')
を呼び出す場合、Pathifyは最初に関連するモジュールでsetFirstName
アクションをチェックします。 存在しない場合は、SET_FIRST_NAME
ミューテーションをチェックし、代わりにそれを使用します。
pathify.sync('data/user/firstName')
を使用すると、これらの動作の両方を1つの計算されたプロパティに組み合わせることができます。 @
構文を使用して、さらにサブプロパティにアクセスできます。 たとえば、user
モジュールがなく、data
モジュールにuserData
プロパティがある場合は、代わりにpathify.sync('data/[email protected]')
を使用できます。同じ効果に。
これにより、commit()
、dispatch()
などに頼る代わりに、一貫性のある単純な構文ですべてのVuex
機能にアクセスできます。
vuex-pathify
の使用方法の詳細については、公式ドキュメントを参照してください。
Vuex-Pathifyの構成
上記の情報は、vuex-pathify
から始めていない場合でも、興味を引くのに十分なはずですが、注意すべきことが1つあります。 モジュールの構成は、通常とは少し異なる方法で行われます。 コンストラクターに渡されたオプションを使用する代わりに、実行時に、vuex-pathify
はプロトタイプのプロパティを変更することによって構成されます。 プラグインを構成するための推奨される方法は次のとおりです。
- ソースディレクトリに
pathify.js
という名前の新しいファイルを作成します。 - pathifyをインポートし、構成値を変更します。
- pathifyを再エクスポートして、
vuex
モジュールで使用します。
変更できるオプションの完全なリストは、こちらで入手できます。
// Import pathify.
import pathify from 'vuex-pathify';
// Mapping: /thing -> getter: thing, mutation: SET_THING, action: setThing
options.mapping = 'standard'; // Default
// Re-export pathify.
export default pathify;
...
import pathify from './pathify'; // instead of from `vuex-pathify.
...