【问题标题】:How to use vuex map helpers in composition api in Nuxt如何在 Nuxt 的组合 API 中使用 vuex 地图助手
【发布时间】:2020-11-03 23:23:11
【问题描述】:

我花了很多时间弄清楚如何使用vuex map helper函数,最后还是没有弄明白。

现在我有这样的东西:

setup (_, { root: { $store } }) {
    onMounted(() => {
      $store.commit('app/setApplicationWidth', innerWidth)
      console.log($store.getters['app/getApplicationWidth'])
    })
  }

那么我如何在组合 API 中使用 mapGetters 和 mapMutations?

我的 vuex 商店是这样的: /store/app.ts

import { GetterTree, MutationTree, ActionTree } from 'vuex'

export const state = () => ({
  appWidth: <Number> 0
})

export type RootState = ReturnType<typeof state>

export const mutations: MutationTree<RootState> = {
  setApplicationWidth (state: any, payload: Number) {
    state.appWidth = payload
  }
}

export const getters: GetterTree<RootState, RootState> = {
  getApplicationWidth (state: any): Number {
    return state.appWidth
  }
}

export const actions: ActionTree<RootState, RootState> = {}

【问题讨论】:

    标签: nuxt.js vuex vue-composition-api


    【解决方案1】:

    一个选项是vuex-composition-helpers here。从我粗略的检查来看,它似乎有效。但是,您可能需要注意一些问题,以便正确地下车:

    1. 您需要通过添加到nuxt.config.js来进行转译:
      build: {
    ...
        transpile: ['vuex-composition-helpers']
      }
    

    否则你会得到一个难以理解的“未知关键字export”错误。

    1. 嵌套存储使用备用 *Namespaced* 方法:
    import { useNamespacedGetters } from 'vuex-composition-helpers'
    
    export default defineComponent({
    ...
      setup(_props, context) {
        const { articles, articlesInfo } = useNamespacedGetters('articles', [
          'articles',
          'articlesInfo',
        ])
    

    总而言之,它只是比在商店直接使用computed 的“原始”方法好一点:

    import { computed } from '@nuxtjs/composition-api'
    ...
        const articles2 = computed(
          () => context.root.$store.getters['articles/articles']
        )
    

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      相关资源
      最近更新 更多