如何无需按钮将Vuex Store计数器值推入Vue-Chart的mydata数组
自动将Store中的计数器值推入Vue-Chart组件的mydata数组
嘿,这事儿很简单!既然你已经通过计算属性拿到了更新后的计数器值,咱们只需要利用Vue的响应式特性,监听这些值的变化,自动把它们推到mydata里就行,完全不用按钮触发。下面是具体步骤:
1. 确保计算属性正确获取Store中的计数器
先确认你的计算属性能实时拿到counter1、counter2、counter3的最新值,比如:
computed: { latestCounters() { return { c1: this.$store.state.counter1, c2: this.$store.state.counter2, c3: this.$store.state.counter3 }; } }
2. 监听计算属性变化,自动更新mydata
用Vue的watch选项监听latestCounters的变化,一旦计数器更新,就把新值推入mydata,同时触发图表重新渲染(这一步很重要,不然vue-chart不会自动更新):
watch: { latestCounters: { deep: true, // 因为监听的是对象,需要开启深度监听 handler(newCounters) { // 把三个计数器值推入mydata数组 this.mydata.push(newCounters.c1, newCounters.c2, newCounters.c3); // 调用vue-chart的renderChart方法更新图表 this.renderChart({ labels: this.mylabels, datasets: [{ label: this.mylabel, data: this.mydata }] }); } } }
3. 初始化时加载初始计数器值(可选)
如果希望页面刚加载时,就把初始的计数器值加入mydata,可以在mounted钩子中做这件事:
mounted() { // 初始推入计数器值 this.mydata.push(this.$store.state.counter1, this.$store.state.counter2, this.$store.state.counter3); // 初始化图表 this.renderChart({ labels: this.mylabels, datasets: [{ label: this.mylabel, data: this.mydata }] }); }
小提示:避免重复添加(可选)
如果你不想每次计数器更新都往mydata里追加,而是想替换掉旧的计数器值(比如始终保留最新的三个),可以修改handler里的逻辑:
handler(newCounters) { // 替换mydata的最后三个元素(或者根据你的需求调整位置) this.mydata = [...this.mydata.slice(0, -3), newCounters.c1, newCounters.c2, newCounters.c3]; this.renderChart({ labels: this.mylabels, datasets: [{ label: this.mylabel, data: this.mydata }] }); }
这样一来,只要其他组件更新了Store里的计数器,你的图表组件就会自动把新值推入mydata并更新图表,完全不需要手动点击按钮~
内容的提问来源于stack exchange,提问作者S. Haider
相关产品推荐
相关产品推荐

