javascript - 如何避免在 Vue 中一直写 this.$store.state.donkey?

标签 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 很痛苦,而且它也降低了可读性。我感觉到我正在以一种不太理想的方式来做这件事。我应该如何引用商店的状态?

最佳答案

您可以为状态和 getter 设置计算属性,即

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

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

为了使事情变得更简单,您可以引入 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

worth noting here that getters, mutations & actions are global - therefore they are referenced directly on your store, i.e. store.getters, store.commit & store.dispatch respectively. This applies whether they are in a module or in the root of your store. If they are in a module check out namespacing to prevent overwriting previously used names: vuex docs namespacing. However if you are referencing a modules state, you must prepend the name of the module, i.e. store.state.user.firstName in this example user is a module.


编辑 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


我整理了一个示例 fiddle 来展示您可以引用和使用 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


添加混合

要扩展上述行为,您可以将其与 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
        ...

关于javascript - 如何避免在 Vue 中一直写 this.$store.state.donkey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909576/

相关文章:

javascript - 为什么我点击播放按钮,它不播放?

javascript - Yeoman Mean.js 生成的自定义 AngularJS 指令不起作用

javascript - Node.js Nodemailer 对象数组到 CSV 文件作为电子邮件中的附件

javascript - Vuejs 如何将数据作为 Prop 传递给子组件

firebase - 使用 Firebase + Vue 构建 Web 应用程序时,我们真的需要 Vuex 吗?

php - 检测重定向的访客

vue.js - v-model 覆盖 VueJS 中的输入值

javascript - 替换整个 vue.js 容器

vue.js - 如何在 v-select 中为 vue-dropdown 显示名称?

api - 如何在 Vue.js 中构造 api 调用?