如何使用vue-chartjs发出事件?

c86crjj0  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(213)

我使用了vue js,并且我用chartjs显示了一个图形。当我点击图形时,我想发出一个事件来获取父组件中的数据。我的onClick函数起作用了,但事件不起作用。你知道我的问题吗?组件Line2.vue

<script>
import { mixins, Line } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
  extends: Line, 
  mixins: [reactiveProp],
  props: ["options"],
  mounted() {
    const self = this;
    console.log(self);
    this.options.onClick = function (e, tooltipItems) {
      console.log(tooltipItems[0].__ob__); //.logged
      self.$emit("sendIndex", tooltipItems[0]._index);
    };
    this.renderChart(this.chartData, this.options);
  },
};
</script>
<style scoped></style>

我的主要组件

...
    <h1 v-on:sendIndex="getIndexCoord($event)">{{ indexCoord }}</h1>
...
methods: {
    getIndexCoord: function (e) {
      console.log("rrr", e); //Not logged
      this.indexCoord = e;
    },
}

此致

ogsagwnx

ogsagwnx1#

1.首先创建EventBus.js文件,从“vue”导入Vue;

export const EventBus = new Vue();

2.在char.js文件中编写如下代码

import { EventBus } from "../EventBus.js";
import { mixins, Line } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
  extends: Line, 
  mixins: [reactiveProp],
  props: ["options"],
  mounted() {
    const self = this;
    console.log(self);
    this.options.onClick = function (e, tooltipItems) {
      console.log(tooltipItems[0].__ob__); //.logged
      EventBus.$emit("sendIndex", tooltipItems[0]._index);
    };
    this.renderChart(this.chartData, this.options);
  },
};

1.您希望在何处访问文件中数据,如下所示

import { EventBus } from "../EventBus.js";
mounted() {

   EventBus.$on('sendIndex', data => {
      console.log(data)
     });

},

相关问题