Vuejs组件通信

时间:2019-01-12 22:45:03

标签: highcharts vuejs2

我正在尝试使用 $ emit $ on 在两个组件之间进行通信:

我无法在两个组件之间进行通信,也无法通过组件A中的点击事件来更新组件B中的 highcharts-chart

组件A的JavaScript代码:

import Vue from 'vue';

const bus = new Vue();

const pause = ms => new Promise(resolve => setTimeout(resolve, ms));


export default {

  data: () => ({
    active: [],
    avatar: null,
    open: [],
    users: [],
  }),

  computed: {
    items() {
      return [
        {
          name: 'Users',
          children: this.users,
        },
      ];
    },
    selected() {
      if (!this.active.length) return undefined;

      const id = this.active[0];

      return this.users.find(user => user.id === id);
    },
  },

  methods: {

    fetchData() {
      const id = this.active[0];
      this.parts = this.users.find(user => user.id === id);
      bus.$emit('new_parts', this.parts.data);
      console.log(this.parts.data);
    },


    async fetchUsers(item) {
      // Remove in 6 months and say
      // you've made optimizations! :)
      await pause(1500);

      return fetch('http://localhost:8081/api/toppartsdata')
        .then(res => res.json())
        .then(json => (item.children.push(...json)))
        .catch(err => console.warn(err));
    },

  },
};

组件B的JavaScript代码:

    import VueHighcharts from 'vue2-highcharts';
import Vue from 'vue';

const bus = new Vue();

const asyncData = {
  name: 'Prediction Chart',
  marker: {
    symbol: 'circle',
  },
  data: [],
};
export default {
  components: {
    VueHighcharts,
  },
  data() {
    return {
      options: {
        chart: {
          type: 'spline',
          title: '',
        },
        xAxis: {
          categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        },
        yAxis: {
          title: {
            text: 'LINECOST',
          },
          labels: {
            formatter() {
              return `${this.value}°`;
            },
          },
        },
        tooltip: {
          crosshairs: true,
          shared: true,
        },
        credits: {
          enabled: false,
        },
        plotOptions: {
          spline: {
            marker: {
              radius: 4,
              lineColor: '#666666',
              lineWidth: 1,
            },
          },
        },
        series: [],
      },
    };
  },
  methods: {
    test() {
      // eslint-disable-next-line func-names

      bus.$on('new_parts', (data) => {
        alert(value);
      });
    },
    load() {
    // eslint-disable-next-line func-names
      bus.$on('new_parts', function (data) {
        this.asyncData.data = data;
      });
      const { lineCharts } = this.$refs;
      lineCharts.delegateMethod('showLoading', 'Loading...');
      setTimeout(() => {
        lineCharts.addSeries(asyncData.data);
        lineCharts.hideLoading();
      }, 2000);
    },
  },
};

我希望能够使用组件A中的单击事件来更新我的图表图表,并且每次单击新按钮时都将事件中的数据更新到组件B中。

4 个答案:

答案 0 :(得分:2)

如果这是您在两个组件中都使用的真实代码,那么它将不起作用,因为您将创建2个不同的总线,而不是将同一总线用于事件。

尝试将其拉出到单独的文件中,例如attempt,然后将其导出并导入到需要与之交互的组件中:

args

让我知道是否有什么不合理的地方。

答案 1 :(得分:0)

最简单的处理方法是使用this。$ root发出并监听事件:

要从组件a发出事件:

this.$root.$emit('new_parts', this.parts.data)

要收听组件b上的事件:

 mounted() {
            this.$root.$on('new_parts', (data) => {
                //Your code here

            });
        },

请在已安装的方法中添加onclick。

这是一篇有关Vue事件的好文章:https://flaviocopes.com/vue-components-communication/

答案 2 :(得分:0)

以下是我的highcharts组件的更新代码:

<template>
  <div>
    <vue-highcharts :options="options" ref="lineCharts"></vue-highcharts>
  </div>
</template>

<script>
import VueHighcharts from 'vue2-highcharts';
import { bus } from '../../../main';


export default {

  props: {
    partsdata: {
      type: Array,
    },
  },


  components: {
    VueHighcharts,

  },
  data() {
    return {

      options: {
        chart: {
          type: 'spline',
          title: 'Hassaan',
        },
        xAxis: {
          categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        },
        yAxis: {
          title: {
            text: '',
          },
          labels: {
            formatter() {
              return `${this.value}°`;
            },
          },
        },
        tooltip: {
          crosshairs: true,
          shared: true,
        },
        credits: {
          enabled: false,
        },
        plotOptions: {
          spline: {
            marker: {
              radius: 4,
              lineColor: '#666666',
              lineWidth: 1,
            },
          },
        },
        series: [],
      },
    };
  },


  created() {
    bus.$on('new_user', (data) => { this.series = data; });
  },

};
</script>

答案 3 :(得分:0)

您的最后一个代码几乎是正确的,但这是错误的部分:

代码错误:

created() {
   bus.$on('new_user', (data) => { this.series = data; });
}

this.series不是指序列数据,而是要向整个组件对象添加一个新属性。在您的情况下,它应如下所示:

正确的代码:

created() {
   bus.$on('new_user', (data) => { this.options.series[0].data = data; });
}

我为您准备了一个在线示例,其中使用了我推荐的 highcharts-vue VUE官方Highcharts包装器。在那里,您将找到在组件之间进行通信的有效代码。

演示:
https://codesandbox.io/s/r0qmqjljwq

相关问题