Skip to content

Vue教程18:组件间通信之二:通过事件通信 #19

Description

@chencl1986

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。

该节教程代码可通过npm start运行devServer,在http://localhost:8080/查看效果

通过$emit触发事件,通过$on接收事件,实现通信

代码示例:/lesson17/src/components/parent.js,/lesson17/src/components/child.js

通过调用组件实例的$emit(事件名, 参数),向组件发送一个事件。
在组件的生命周期created中,使用\this.$on(事件名, 回调函数),在回调函数中可以接收到参数,以此实现组件间通信。

父组件代码:

export default Vue.component('parent', {
  data() {
    return {
      num: 0,
    };
  },
  components: {
    Child
  },
  created() {
    this.$on('add', function (n) {
      this.num = this.num + n
    })
  },
  methods: {
    addChild() {
      this.$refs.child.$emit('add', 5)
    },
  },
  template: `
    <div>
      <div>父级
      num:{{num}}
      <br/><input type="button" value="子级num1 + 5" @click="addChild" />
      <child ref="child" :parent="this"></child>
    </div>
  `
});

子组件代码:

export default Vue.component('parent', {
  props: ['parent'],
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    addParent() {
      this.parent.$emit('add', 5)
    },
  },
  created() {
    this.$on('add', function (n) {
      this.num = this.num + n
    })
  },
  template: `
    <div>
      子级
      num:{{num}}
      <br/><input type="button" value="父级num1 + 5" @click="addParent" />
    </div>
  `
});

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions