如何在脚本中使用 VUEX GETTERS

How to use VUEX GETTERS in script

我正在为一些变量使用 VUEX GETTERS。我可以在 html 部分使用它们,但我不能在脚本->数据部分编辑或更改它们。

错误:[Vue 警告]:数据错误():“ReferenceError:未定义位置”

<script>
import {mapGetters} from 'vuex'
export default {
        data: () => ({
            dialog: false,
            TotalEntitiy:Positions[0] // GIVES ERROR
        }),       
        computed:{
            ...mapGetters({
                PageTitle:  'GETTER_CURRENT_PAGE',
                headers:   'GETTER_HEADERS',
                Positions: 'GETTER_POSITIONS',
                items:'GETTER_ITEMS'
            }),

定义 TotalEntity 一个新的计算 属性 而不是组件数据的一部分,因为它必须根据存储中的值进行反应:

data: () => ({
    dialog: false
}),       
computed:{
    ...mapGetters({
        PageTitle:  'GETTER_CURRENT_PAGE',
        headers:   'GETTER_HEADERS',
        Positions: 'GETTER_POSITIONS',
        items:'GETTER_ITEMS'
    }),
    TotalEntity() {
        return this.Positions[0];
    }
}

更新:为了避免 this.Positions 可能是 nullundefined 的潜在问题,您可以使用 optional chaining operator ?.:

return this.Positions?.[0];

您还可以使用 nullish coalescing operator 回退到默认值:

return this.Positions?.[0] ?? YOUR_FALLBACK_VALUE;