11

私は Vue を学んでいますが、多かれ少なかれどこにでも次の構文があることに気付きました。

export default {
  components: { Navigation, View1 },
  computed: {
    classObject: function() {
      return {
        alert: this.$store.state.environment !== "dev",
        info: this.$store.state.environment === "dev"
      };
    }
  }
}

this.$store.state.donkeyいつも書き出すのは面倒で、読みやすさも低下します。私はそれを最適とは言えない方法で行っていることを感じています。店舗の状態はどのように参照すればよいですか?

4

1 に答える 1

22

状態とゲッターの両方に計算されたプロパティを設定できます。

computed: {
    donkey () {
        this.$store.state.donkey
    },
    ass () {
        this.$store.getters.ass
    },
    ...

$state.store を呼び出す必要がありますが、VM でロバやロバを参照できるようになったら...

物事をさらに簡単にするために、vuex マップ ヘルパーを取り込み、それらを使用してお尻を見つけることができます...またはロバ:

import { mapState, mapGetters } from 'vuex'

default export {

    computed: {

        ...mapState([
            'donkey',
        ]),

        ...mapGetters([
            'ass',
        ]),

        ...mapGetters({
            isMyAss: 'ass', // you can also rename your states / getters for this component
        }),

今あなたが見れば、this.isMyAssあなたはそれを見つけるでしょう...あなたのass

ここで、getter、mutation、および action はグローバルであることに注意してください。したがって、これらはストアで直接参照されます。つまりstore.getters、それぞれstore.commit&store.dispatchです。これは、それらがモジュール内にあるかストアのルートにあるかに関係なく適用されます。それらがモジュール内にある場合は、名前空間をチェックして、以前に使用された名前を上書きしないようにします: vuex docs namespaces。ただし、モジュールの状態を参照している場合は、モジュールの名前を先頭に追加する必要があります。つまりstore.state.user.firstName、この例userではモジュールです。


編集 23/05/17

これを書いている時点から Vuex は更新されており、その名前空間機能は、モジュールを操作する際に利用できるようになりました。namespace: trueモジュールのエクスポートに追加するだけです。

# vuex/modules/foo.js
export default {
  namespace: true,
  state: {
    some: 'thing',
    ...

fooモジュールを vuex ストアに追加します。

# vuex/store.js
import foo from './modules/foo'

export default new Vuex.Store({

  modules: {
    foo,
    ...

次に、このモジュールをコンポーネントにプルするときに、次のことができます。

export default {
  computed: {
    ...mapState('foo', [
      'some',
    ]),
    ...mapState('foo', {
      another: 'some',
    }),
    ...

これにより、モジュールが非常にシンプルで使いやすくなり、複数レベルの深さでモジュールをネストしている場合、真の救世主になります: namespaces vuex docs


vuex ストアを参照して操作するさまざまな方法を紹介するために、フィドルの例をまとめました。

JSFiddle Vuex の例

または、以下をチェックしてください。

const userModule = {

	state: {
        firstName: '',
        surname: '',
        loggedIn: false,
    },
    
    // @params state, getters, rootstate
    getters: {
   		fullName: (state, getters, rootState) => {
        	return `${state.firstName} ${state.surname}`
        },
        userGreeting: (state, getters, rootState) => {
        	return state.loggedIn ? `${rootState.greeting} ${getters.fullName}` : 'Anonymous'
        },
    },
    
    // @params state
    mutations: {
        logIn: state => {
        	state.loggedIn = true
        },
        setName: (state, payload) => {
        	state.firstName = payload.firstName
        	state.surname = payload.surname
        },
    },
    
    // @params context
    // context.state, context.getters, context.commit (mutations), context.dispatch (actions)
    actions: {
    	authenticateUser: (context, payload) => {
        	if (!context.state.loggedIn) {
        		window.setTimeout(() => {
                	context.commit('logIn')
                	context.commit('setName', payload)
                }, 500)
            }
        },
    },
    
}


const store = new Vuex.Store({
    state: {
        greeting: 'Welcome ...',
    },
    mutations: {
        updateGreeting: (state, payload) => {
        	state.greeting = payload.message
        },
    },
    modules: {
    	user: userModule,
    },
})


Vue.component('vuex-demo', {
	data () {
    	return {
        	userFirstName: '',
        	userSurname: '',
        }
    },
	computed: {
    
        loggedInState () {
        	// access a modules state
            return this.$store.state.user.loggedIn
        },
        
        ...Vuex.mapState([
        	'greeting',
        ]),
        
        // access modules state (not global so prepend the module name)
        ...Vuex.mapState({
        	firstName: state => state.user.firstName,
        	surname: state => state.user.surname,
        }),
        
        ...Vuex.mapGetters([
        	'fullName',
        ]),
        
        ...Vuex.mapGetters({
        	welcomeMessage: 'userGreeting',
        }),
        
    },
    methods: {
    
    	logInUser () {
        	
            this.authenticateUser({
            	firstName: this.userFirstName,
            	surname: this.userSurname,
            })
        	
        },
    
    	// pass an array to reference the vuex store methods
        ...Vuex.mapMutations([
        	'updateGreeting',
        ]),
        
        // pass an object to rename
        ...Vuex.mapActions([
        	'authenticateUser',
        ]),
        
    }
})


const app = new Vue({
    el: '#app',
    store,
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>

<div id="app">

    <!-- inlining the template to make things easier to read - all of below is still held on the component not the root -->
    <vuex-demo inline-template>
        <div>
            
            <div v-if="loggedInState === false">
                <h1>{{ greeting }}</h1>
                <div>
                    <p><label>first name: </label><input type="text" v-model="userFirstName"></p>
                    <p><label>surname: </label><input type="text" v-model="userSurname"></p>
                    <button :disabled="!userFirstName || !userSurname" @click="logInUser">sign in</button>
                </div>
            </div>
            
            <div v-else>
                <h1>{{ welcomeMessage }}</h1>
                <p>your name is: {{ fullName }}</p>
                <p>your firstName is: {{ firstName }}</p>
                <p>your surname is: {{ surname }}</p>
                <div>
                    <label>Update your greeting:</label>
                    <input type="text" @input="updateGreeting({ message: $event.target.value })">
                </div>
            </div>
        
        </div>        
    </vuex-demo>
    
</div>

ご覧のとおり、ミューテーションまたはアクションをプルしたい場合、これは同様の方法で行われますが、メソッドではmapMutationsorを使用しますmapActions


ミックスインの追加

上記の動作を拡張するには、これを mixin と組み合わせることができます。その後、上記の計算されたプロパティを一度設定し、それらを必要とするコンポーネントに mixin を取り込むだけで済みます。

Animals.js (ミックスイン ファイル)

import { mapState, mapGetters } from 'vuex'

export default {

    computed: {

       ...mapState([
           'donkey',
           ...

あなたのコンポーネント

import animalsMixin from './mixins/animals.js'

export default {

    mixins: [
        animalsMixin,
    ],

    created () {

        this.isDonkeyAnAss = this.donkey === this.ass
        ...
于 2016-12-01T13:45:01.490 に答える