【发布时间】:2021-07-28 08:25:19
【问题描述】:
我用 VueX 做了一个 VueJS 3 项目来存储数据。
当我在下面的代码中打印变量 data.doughnutChart.data 时,它会显示
{ “标签”:[“确定”、“警告”、“错误”]、“数据集”:[{ “背景颜色”:[“#d4efdf”,“#fdebd0”,“#fadbd8”],“数据”:[3, 1, 2 ] } ] }
但是图表没有使用这些数据[3,1,2],图表使用了VueX的index.js中初始化的值。 这是我的代码:
<template>
{{data.doughnutChart.data}}
<div style="height:200px;width: 200px; position:center">
<vue3-chart-js
:id="data.doughnutChart.id"
:type="data.doughnutChart.type"
:data="data.doughnutChart.data"
:options="data.doughnutChart.options"
></vue3-chart-js>
</div>
</template>
<script>
import Vue3ChartJs from '@j-t-mcc/vue3-chartjs'
export default {
name: 'App',
components: {
Vue3ChartJs,
},
beforeMount() {
this.$store.dispatch("getData");
},
computed: {
data() {
return {
doughnutChart: {
id: 'doughnut',
type: 'doughnut',
data: {
labels: ['OK', 'WARNING', 'ERROR'],
datasets: [
{
backgroundColor: [
'#d4efdf',
'#fdebd0',
'#fadbd8'
],
data: [this.$store.state.nbOk, this.$store.state.nbWarning, this.$store.state.nbError]
}
]
},
options:
{
plugins: {
legend: {
display: false
},
title: {
display: true,
text: 'Current situation'
}
},
}
}
}
}
}
}
</script>
我在我的 index.js (VueX) 中读取了值:
import axios from 'axios'
import { createStore } from 'vuex'
export default createStore({
state: {
data: [],
nbError : 0,
nbWarning : 0,
},
actions: {
getData({commit}){
axios.get('http://localhost:8080/data/mock.json')
.then(res => {
commit('SET_DATA', res.data)
})}
},
mutations: {
SET_DATA(state, data){
state.data = data.data;
state.nbWarning = 0;
state.nbError = 0;
for (let i = 0; i < state.data.length; i++) {
if(state.data[i].status == 'WARNING'){
state.nbWarning += 1;
};
if(state.data[i].status == 'ERROR'){
state.nbError += 1;
};
};
}
})
但是,在我的 Vuejs 项目中,当我进入另一个页面并返回时它会起作用,但当我只是打开项目或刷新页面时就不行。
你知道为什么吗?
【问题讨论】: