Vue项目vue-chartjs饼图无法接收输入值、数据更新不生效问题
问题解决方案
先修复已知笔误
takeMoney方法中存在变量名拼写错误,将BCT改为BTC,否则BTC数值不会更新:
takeMoney() { this.USD -= this.myMoney this.ETH -= this.myMoney * 0.0003 // 修正拼写错误 this.BTC -= this.myMoney * 0.000017 },
1. 父组件向PieExample传递数据
Page.vue修改
首先在父组件模板中引入子组件时,通过props传递你需要渲染的三个数值,同时补充输入框和操作按钮的绑定逻辑:
<template> <div> <input v-model.number="myMoney" type="number" placeholder="输入金额"> <button @click="addMoney">存入</button> <button @click="takeMoney">取出</button> <!-- 传递动态数据给子组件 --> <PieExample :usd="USD" :eth="ETH" :btc="BTC" /> </div> </template> <script> import PieExample from '../components/PieExample' export default { components: { PieExample, }, data () { return { myMoney: null, USD: 0, ETH:0, BTC:0 } }, methods: { addMoney() { if(!this.myMoney) return this.USD += this.myMoney this.ETH += this.myMoney * 0.0003 this.BTC += this.myMoney * 0.000017 }, takeMoney() { if(!this.myMoney) return this.USD -= this.myMoney this.ETH -= this.myMoney * 0.0003 this.BTC -= this.myMoney * 0.000017 }, }, } </script>
2. 饼图数据同步更新修改
PieExample.js修改
子组件需要先接收父组件传入的props,然后监听props变化,每次数据更新时销毁旧图表实例,重新渲染新的图表:
import { Pie } from 'vue-chartjs' export default { extends: Pie, // 接收父组件传入的数值 props: { usd: { type: Number, default: 0 }, eth: { type: Number, default: 0 }, btc: { type: Number, default: 0 } }, mounted () { // 初始化渲染图表 this.renderPieChart() }, watch: { // 监听三个数值变化,变化时重新渲染图表 usd: 'renderPieChart', eth: 'renderPieChart', btc: 'renderPieChart' }, methods: { renderPieChart() { // 销毁旧图表实例,避免重复渲染报错 if(this.$data._chart) { this.$data._chart.destroy() } this.renderChart({ labels: ['USD', 'ETH', 'BTC'], datasets: [ { backgroundColor: [ '#41B883', '#E46651', '#00D8FF', ], // 用父组件传入的动态数据替换写死的静态数据 data: [this.usd, this.eth, this.btc] } ] }, {responsive: true, maintainAspectRatio: false}) } } }
内容的提问来源于stack exchange,提问作者Exterminator
相关产品推荐
相关产品推荐

