Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

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

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的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>
  `
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant