如何避免在Vue中一直写这个。$ store.state.donkey?

时间:2016-12-01 11:31:47

标签: javascript vue.js vuex

我正在学习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会很痛苦,也会降低可读性。我感觉到我的做法不是那么理想。我应该如何参考商店的状态?

1 个答案:

答案 0 :(得分:17)

您可以为这两种状态设置计算属性。 getters,即

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

虽然你仍然需要调用$ state.store然后你可以在你的虚拟机上引用驴或驴......

为了让事情变得更加容易,您可以拉入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

  

值得注意的是,吸气剂,突变和行为是全球性的 - 因此它们会直接在您的商店中引用,即store.gettersstore.commit&分别为store.dispatch。这适用于它们是在模块中还是在商店的根目录中。如果它们在模块中,请检查命名空间以防止覆盖以前使用的名称:vuex docs namespacing。但是,如果要引用模块状态,则必须添加模块的名称,即此示例中的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',
    }),
    ...

这使得模块使用起来非常简单和干净,如果你将它们嵌套在多个深层,它们是一个真正的救星:namespacing vuex docs

我已经汇集了一个示例小提示,以展示您可以参考和使用您的vuex商店的各种方式:

<强> JSFiddle Vuex Example

或者查看以下内容:

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>

正如您所看到的,如果您想要引入突变或操作,这将以类似的方式完成,但在您的方法中使用mapMutationsmapActions

添加Mixins

要扩展上述行为,你可以将它与mixin结合起来,然后你只需要设置一次上面的计算属性并在需要它们的组件上拉入mixin:

animals.js (mixin档案)

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
        ...