javascript - Vue 页面中的 Chart.js 抛出错误:不要在突变处理程序之外改变 vuex 存储状态
问题描述
我有一个 Nuxt/Vue 应用程序,其页面显示图表。该页面还包含
- 允许用户创建新数据点的模态组件
- 一个下拉菜单,允许用户选择他们希望图表显示多少天的数据。
我想实现以下目标:
- 创建新数据条目后刷新页面(再次调用我的 API)
- 当用户选择不同的下拉值时刷新页面
我现在面临的主要问题是条形图在我关闭数据输入模式后几秒钟消失了,我可以在控制台中看到以下错误:Error: [vuex] do not mutate vuex store state outside mutation handlers.
.
此外,我似乎无法通过更改下拉值来触发更新,但这是我的次要问题。
由于此示例涉及外部 API,因此很难提出可重现的示例,但我的设置如下所示:
<template>
...
<select v-model="chartSelection", :oninput="refreshChart">
<option value="0">7 days</option>
<option value="1">14 days</option>
</select>
<bar-chart :data="chartData" :options="chartOptions"/>
<Modal v-if="showModal">
<!--
This is a custom component with its own modalToggle function.
It opens a form that allows you to create a new data point.
When this modal is closed, I would like to refresh the page
over which this modal appears
-->
...
</template>
...
<script>
async function getData(axios, store, period){
const data = await axios.get(`my/endpoint/${period}`)
const chartData = {
labels: data.data.dates,
datasets: [
{backgroundColor: 'red', label: 'A', data.data.a},
{backgroundColor: 'blue', label: 'B', data.data.b},
]
}
store.commit('saveChartData', chartData) // a simple assignment mutation in vuex
}
...
export default {
async asyncData({$axios, store}) {
await getData($axios, store, '7')
},
methods: {
refreshChart() {
return getData(this.$axios, this.$store, this.days)
}
},
data() {
return {
chartSelection: '0', // this should determined how much data we fetch
}
}
},
computed: {
...mapState(['chartData', 'showModal']),
days() {
return this.chartSelection == '0' ? '7' : '14'
}
}
...
</script>
如果有人对如何解决此问题有任何建议,请告诉我!
编辑:
仅供参考,该模式仅显示一个将图表数据提交给 API 的表单。上面示例中的bar-chart
chart.js 插件如下所示:
import Vue from 'vue'
import Bar from 'vue-chartjs'
const registerComponent = function (name, originalComponent) {
Vue.component(name, {
extends: originalComponent,
props: ['data', 'options'],
mounted() {
this.renderChart(this.data, this.options)
},
})
}
解决方案
关于图表更新:
当数据点添加到模态中时,向父组件发出一个自定义事件,该事件将调用 getData。
<Modal v-if="showModal" @dataPointAdded="getData">
在模态中:
AddDataPoint(data) {
/* Add data point */
this.$emit("dataPointAdded");
}
要使用新数据更新图表组件 - 添加观察者:
props: ['data', 'options'],
mounted() {
this.renderChart(this.data, this.options)
},
watch:
{
data() {
this.$data._chart.update();
},
options() {
this.$data._chart_update();
}
}
推荐阅读
- sockets - 如何在 SWI Prolog 中向 tcp 套接字发出请求并处理响应?
- neo4j - Neo4J 转储数据库
- github - 有没有办法查看 github 存储库从公共切换到私有的日期,反之亦然
- reactjs - Bootstrap 不能像使用 React.js(springboot API)那样使用构建
- javascript - JavaScript 扩展 - 用鼠标将多个 YouTube 视频标记为“无趣”
- excel - 如何从活动单元格中选择基于 A 列的最后一个条目?
- asp.net-core - 缺少客户端密钥或客户端证书
- git - 无法使用 Windows 使用 ssh 密钥访问 gitlab 存储库
- c - 通过 fgets 在 c 中的 while 循环中输入一个数字
- javascript - 为什么 tr 中的 onClick 方法没有调用 foreach Laravel 5 中的函数