首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vuejs组件通信

Vuejs组件通信
EN

Stack Overflow用户
提问于 2019-01-12 22:45:03
回答 4查看 457关注 0票数 0

我试图使用$emit$on在两个组件之间进行通信。

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

组件的JavaScript代码-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));
    },

  },
};

组件的JavaScript代码-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每次单击新按钮。

EN

回答 4

Stack Overflow用户

发布于 2019-01-13 00:53:10

如果这是您在两个组件中使用的真正代码,那么它就无法工作,因为您正在创建两个不同的总线,而不是在事件中重用相同的总线。

尝试在一个单独的文件(例如bus.js )中取出它,然后导出它并在需要与它交互的组件中导入它:

代码语言:javascript
复制
// bus.js
export default new Vue()

// Component A
import bus from './bus'

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

// Component B
import bus from './bus'

bus.$on('new_parts', (data) => {
  alert(value);
})

如果有什么不合理的话请告诉我。

票数 2
EN

Stack Overflow用户

发布于 2019-01-13 05:04:31

最简单的处理方法是使用this.$root来发出和侦听事件:

若要从组件-a发出事件:

代码语言:javascript
复制
this.$root.$emit('new_parts', this.parts.data)

要收听构成部分b上的活动:

代码语言:javascript
复制
 mounted() {
            this.$root.$on('new_parts', (data) => {
                //Your code here

            });
        },

请在挂载方法中添加onclick。

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

票数 0
EN

Stack Overflow用户

发布于 2019-01-13 22:24:36

下面的是我的高级图表组件的更新代码:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54164555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档