如何分配 mapState 数据列表?

How to assign mapState list of data?

目前,我正在研究 apex 条形图,想将 mapState 数据列表分配到 apex 系列数据中。

代码如下:

<script>
import { mapState } from 'vuex';
export default {
  data: () => ({
    series: [{
              name: 'Completed',
              data: [44, 55, 57, 58, 56, 61, 58, 63, 60, 66, 67, 62]
            }, {
              name: 'Total',
              data: [100, 90, 101, 100, 98, 87, 105, 97, 114, 94, 112, 100]
          }]
    }),
computed: {
      ...mapState(['userAssignmentProgessTotal','userAssignmentProgessCompleted']),
    },
}
</script>
mapState value:
userAssignmentProgessTotal: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
userAssignmentProgessCompleted: [45, 29, 32, 17, 1, 13, 12, 10, 8, 8, 8, 8]

我想像下面这样分配:

series: [{
              name: 'Completed',
              data: this.userAssignmentProgessTotal
            }, {
              name: 'Total',
              data: this.userAssignmentProgessCompleted
          }]

但出现错误:

Error in data(): "TypeError: Cannot read property 'userAssignmentProgessTotal' of undefined"

我对 vuex 和 vuejs 都很陌生。如果我没有描述好,请道歉。谢谢

截图:

[1] If you want the series to be reactive ie. keep changing / updating when userAssignmentProgessTotal or userAssignmentProgessCompleted changes, make series a computed property instead of data property

import { mapState } from 'vuex';

export default {
  computed: {  
    ...mapState([
      'userAssignmentProgessTotal',
      'userAssignmentProgessCompleted'
    ]),
    series () {
      return [{
        name: 'Completed',
        // If `userAssignmentProgessTotal` is any falsy value it will return the default array else will return `userAssignmentProgessTotal`
        data: this.userAssignmentProgessTotal || [44, 55, 57, 58, 56, 61, 58, 63, 60, 66, 67, 62]
      }, {
        name: 'Total',
        data: this.userAssignmentProgessCompleted || [100, 90, 101, 100, 98, 87, 105, 97, 114, 94, 112, 100]
      }]
    }
  }
}

[2] If you want to manually update series, make a method to update series

import { mapState } from 'vuex';

export default {
  data () {
    return {
      series () {
        return [{
          name: 'Completed',
          data: [44, 55, 57, 58, 56, 61, 58, 63, 60, 66, 67, 62]
        }, {
          name: 'Total',
          data: [100, 90, 101, 100, 98, 87, 105, 97, 114, 94, 112, 100]
        }]
      }
    }
  },

  computed: {
    ...mapState([
      'userAssignmentProgessTotal',
      'userAssignmentProgessCompleted'
    ])
  },

  methods: {
    updateSeries () {
      this.$set(this.series, 0, { name: this.series[0].name, data: this.userAssignmentProgessTotal })
      this.$set(this.series, 1, { name: this.series[1].name, data: this.userAssignmentProgessCompleted })
    }
  },

  mounted () {
    // call dispatches to fetch data
    // ...
    // call the method in mounted to update series when component loads 
    // or else whenever you want to update series
    this.updateSeries()  
  }
}