我正在创建一个基本的SPA,但碰巧我用Vuex管理的状态和上面的Mutations 都是正确的,但是在我想要使用mapState和MapTranslations的每个组件中,我必须在本地导入它们.

<script>
    import {mapState,mapMutations  } from 'vuex';
    export default{
        computed : mapState(['isLoggedIn']),
        methods: {
            ...mapMutations(['logout'])
        }
    }
</script>

这是正确的方法吗?或者,我如何在全局声明它们,并避免在每个组件中导入它们,以便如下所示?

<script>   

    export default{
        computed : mapState(['isLoggedIn']),
        methods: {
            ...mapMutations(['logout'])
        }
    }
</script>

推荐答案

快速解决方案

Vuex助手(如mapMutations等)返回一个填充了函数的对象,该函数假定this.$store是Vuex存储.

store 服务

如果需要在vanilla JS中使用store,并且不想在任何地方公开store模块,那么可以定义一个服务模块.

import { mapActions } from 'vuex';
import $store from '@/store';

/**
 * Simple mapping of the Vuex store UI module.
 * @module services/ui
 * @property {Function} pushMessage
 */
export default Object.assign({
    $store,
}, mapActions('ui', ['pushMessage']));

现在,使用它就像导入服务模块一样简单.

import ui from './services/ui';

// triggers the `pushAction` on the ui namespaced store module
ui.pushMessage({ content: 'whatever' });

Vue mixin

要在Vue组件上计算默认值和方法,可以创建一个简单的mixin来导入特定组件.

import { mapState, mapMutations } from 'vuex';

export default {
    computed : mapState(['isLoggedIn']),
    methods: mapMutations(['logout'])
}

然后,在组件中使用mixin.

<script>
import mixin from './mixin';

export default {
  mixins: [mixin],
  data() {/* ... */},
  // etc.
}
</script>

全局混合蛋白

如果您真的希望每个组件都有这个默认的mixin,而不必显式地定义它,请使用全局mixin.

import Vue from 'vue';
import { mapState, mapMutations } from 'vuex';

export const mixin = {
    computed : mapState(['isLoggedIn']),
    methods: mapMutations(['logout'])
};

Vue.mixin(mixin);

Personally, as a standard, I never map the state or mutations.

I only map getters and actions so my components don't need to know the state structure and that an action is async or not. I see getters and actions as the public API of a Vuex store (or any similar store, like Redux).

I also only map the relevant data. Components responsibility is to interact with the user of the app, displaying and handling events and nothing more. If all your components need the 100 object, maybe they're doing too much and that logic should probably be moved elsewhere, like in an action.

See more on 100

Vue.js相关问答推荐

为什么 Vue 在将设置脚本中的计算(computed)属性渲染到模板时找不到变量

如何在 Nuxt3 中使用 nuxtjs/auth-next 模块?

如何在Vue js 3中根据API响应替换react 值

Vuejs - 更新数组中对象的数组

webpack vue-loader 配置

Axios Intercept 在第一次调用时未从 localStorage 应用令牌

使用 Laravel 作为后端刷新 Vue.js SPA 的身份验证令牌

如何从 Vuex 状态使用 Vue Router?

Vuetify - 如何保持第一个扩展面板默认打开,如果我打开另一个面板,其他面板应该关闭?

如何为 Vue 项目设置 lint-staged?

Vue.js 中 Chrome 和 Datalist 的性能问题

VueJS 禁用特定属性的react性

如何将 mapActions 与 vue + Typescript 类组件一起使用?

JavaScript/VueJS:判断数组是否包含具有特定值元素的对象

我可以在 Vue 实例方法中传播的 mapMutations 中使用this吗?

Vue.js:TypeError:无法设置只有 getter 的 # 的属性props

Vue 3 组合 API,如何在 setup() 函数中获取上下文父属性?

Vue CLI - 将构建输出组合到单个 html 文件

异步api调用后如何使用vuex getter

Vue中的嵌套循环