我正在学习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是件痛苦的事,而且它也降低了可读性.我感觉到我做这件事的方式不太理想.我应该如何参考store 的状态?

推荐答案

您可以为这两种状态设置计算(computed)属性&;盖特斯.

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

同时你还需要给州政府打电话.存储一次,你就可以在你的虚拟机上引用一头驴或一头驴...

为了让事情变得更简单,你可以使用vuex map 助手来找到你的屁股...或者驴子:

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

值得一提的是,获得者、Mutations 和;行动是全球性的——因此它们直接在您的店铺上引用,即store.gettersstore.commit和;分别是store.dispatch.这适用于它们是在模块中还是在store 的根目录中.如果它们在模块中,请判断名称空间以防止覆盖以前使用的名称:vuex docs namespacing.但是,如果您引用的是模块状态,则必须在模块名称前加上前缀,即在本例中,store.state.user.firstName user是一个模块.


Edit 23/05/17

自从编写Vuex以来,它的名称空间功能已经得到了更新,现在,当您使用模块时,就可以使用它了.只需在模块导出中添加namespace: true,即.

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

foo模块添加到vuex应用store :

# 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层,这将是一个真正的救世主


我制作了一个提琴示例,展示了您可以参考和使用vuexstore 的各种方式:

100

或者查看以下内容:

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>

As you can see if you wanted to pull in mutations or actions this would be done in a similar way but in your methods using 100 or 101


Adding Mixins

要扩展上述行为,可以将其与mixin耦合,然后只需设置上述计算(computed)属性一次,并在需要它们的组件上引入mixin:

animals.js(混合文件)

import { mapState, mapGetters } from 'vuex'

export default {

    computed: {

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

your component

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

export default {

    mixins: [
        animalsMixin,
    ],

    created () {

        this.isDonkeyAnAss = this.donkey === this.ass
        ...

Vue.js相关问答推荐

获取深度嵌套对象时无法读取空/未定义的属性

为什么v-show需要组件的包装元素?

我可以手动访问 vue-router 解析器吗?

Vue 3 / Vuetify 3:如何为按钮设置全局默认 colored颜色

Vue 脚本标签中更漂亮的 destruct 功能

如何在 A-La-Carte 系统中使用 vuetify 加载程序时导入 vuetify/lib

将函数作为属性传递给 Vue 组件

在 dom 内移动 Vue 组件?

Vuex:如何等待动作完成?

为什么组件在 v-if 下没有被销毁

VueJS + Typescript:类型上不存在属性

如何使用 vue.js 获取所选选项的索引

如何使用 TypeScript 在 Vue.js 中指定非react性实例属性?

动态注册本地 Vue.js 组件

如何在 vue.config.js 中为生产设置 API 路径?

VueJS错误编译模板

VueJS 2 在多个组件上debounce

更改时(change)调用函数

在 VueJS 中使用 Axios - 这个未定义

Vuejs 不会在 HTML 表格元素中呈现组件