【问题标题】:Vue dynamic mapGettersVue动态mapGetters
【发布时间】:2019-03-05 18:47:52
【问题描述】:

我有一个道具,我想用它来制作动态 mapGetters,但 mapGetters 将道具视为未定义,可能是因为计算是在道具之前加载的。有人知道我怎样才能使它动态吗?我的代码如下:

export default {
    props: ['listType'],
    components: {
        addrow: AddRow
    },
    computed: {
        ...mapGetters({
            list: `${this.listType}/list`,
            current: 'Dropdown/current'
        }) 
    },
}

【问题讨论】:

  • 在不使用this 关键字的情况下尝试列表:`${listType}/list
  • 我试过了,但我得到一个错误:listType is not defined
  • 你试过了吗list:this.listType+'/list'
  • 你能展示如何调用父组件中的组件吗?
  • 感谢您的回复,当我尝试 list:this.listType+'/list' 然后它仍然未定义,当我 console.log 挂载的 listType 它工作正常,它未定义,因为已加载计算在道具和一切之前,我只是好奇是否有一个 vue 函数或其他东西来存档这个。

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

[更新] 感谢@boussadjrabrahim,我找到了解决方案 我的工作代码如下所示:

export default {
    props: ['listType'],
    components: {
        addrow: AddRow
    },
    computed: {
        ...mapGetters({
            current: 'Dropdown/current'
        }), 

        ...mapState({
            list (state, getters) {
                return getters[`${this.listType}/list`]
            }
        })
    }
}

【讨论】:

  • 非常适合吸气剂。关于如何为行动执行此操作的任何想法?
【解决方案2】:

您还可以使用this.$store 来完全访问商店。所以,list 会变成

export default {
    props: ['listType'],
    computed: {
        list() {
            return this.$store.getters[`${this.listType}/list`]
        }
    }
}

使用dispatch方法触发一个动作,像这样

export default {
    props: ['listType'],
    methods: {
        sortList(order) {
            this.$store.dispatch(`${this.listType}/list`, order)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2020-09-21
    • 2018-05-19
    • 2021-11-13
    • 2020-11-22
    • 2018-02-16
    • 2020-06-22
    相关资源
    最近更新 更多