We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
该节教程代码可通过npm start运行devServer,在http://localhost:8080/查看效果
代码示例:/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> ` });
The text was updated successfully, but these errors were encountered:
No branches or pull requests
阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
通过$emit触发事件,通过$on接收事件,实现通信
通过调用组件实例的$emit(事件名, 参数),向组件发送一个事件。
在组件的生命周期created中,使用\this.$on(事件名, 回调函数),在回调函数中可以接收到参数,以此实现组件间通信。
父组件代码:
子组件代码:
The text was updated successfully, but these errors were encountered: