Vuex-pathifyでVuexBeastを飼いならす

提供:Dev Guides
移動先:案内検索

Fluxアーキテクチャの実装に関する限り、Vue.jsのVuexは最も単純ですが、最もエレガントなものの1つです。 ただし、それでもなお良い可能性があります。 ストア内のすべてのプロパティに対してゲッターとミューテーションを作成することを忘れないようにしようとすると、少し不必要な認知的オーバーヘッドのように見えます。 また、ゲッター、ミューテーション、アクションを手動でマッピングする必要があるのはなぜですか? commitdispatchの違いは何でしたか? vuex-pathify by Dave Stewart は、Vuex機能用の単純なラッパーを提供し、慣例に依存して定型文を減らすことにより、この精神的なオーバーヘッドをすべて削減しようとします。

この記事は、VuexがすでにセットアップされているVue.jsプロジェクトがあり、それがどのように機能するかの基本を知っていることを前提としています。 そうでない場合は、Vuexガイドをご覧ください。

vuex-pathifyをインストールします

まず最初に、pathifyをインストールして、ベースのVuexストア構成でプラグインとして有効にします。

$ npm install --save vuex-pathify

次に、ストアでプラグインを有効にします。

main.js(例)

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セットアップを見てみましょう。 双方向のデータバインディングを使用して、名前と名前を編集できる小さなフォームです。

main.js

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');

App.vue

<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でも同じことを見てみましょう。

main.js

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');

App.vue

<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/userData@firstName')を使用できます。同じ効果に。

これにより、commit()dispatch()などに頼る代わりに、一貫性のある単純な構文ですべてのVuex機能にアクセスできます。

vuex-pathifyの使用方法の詳細については、公式ドキュメントを参照してください。

Vuex-Pathifyの構成

上記の情報は、vuex-pathifyから始めていない場合でも、興味を引くのに十分なはずですが、注意すべきことが1つあります。 モジュールの構成は、通常とは少し異なる方法で行われます。 コンストラクターに渡されたオプションを使用する代わりに、実行時に、vuex-pathifyはプロトタイプのプロパティを変更することによって構成されます。 プラグインを構成するための推奨される方法は次のとおりです。

  1. ソースディレクトリにpathify.jsという名前の新しいファイルを作成します。
  2. pathifyをインポートし、構成値を変更します。
  3. pathifyを再エクスポートして、vuexモジュールで使用します。

変更できるオプションの完全なリストは、こちらで入手できます。

pathify.js(新しいファイル)

// 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;

main.js

...
import pathify from './pathify'; // instead of from `vuex-pathify.
...