How to realize data Exchange between parent and Child components in vuejs
Today, I would like to share with you the relevant knowledge points about how to achieve data interaction between parents and children in vuejs. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
The data interaction between parent and child components follows:
Props down-the child component accepts the data of the parent component through props
Events up-the parent component listens for events of the child component $emit to manipulate the data
Example
The $emit custom event in the click event function of the child component
Export default {name: 'comment', props: [' issue','index'], data () {return {comment:',}}, components: {}, methods: {removeComment: function (index,cindex) {this.$emit ('removeComment', {index:index, cindex:cindex});}, saveComment: function (index) {this.$emit (' saveComment', {index:index, comment: this.comment}); this.comment= " }}, / / hook created: function () {/ / get init data}}
Parent component listens for events
The copy code is as follows:
Event handlers are defined in the methods of the parent component
RemoveComment: function (data) {var index = data.index, cindex = data.cindex; var issue = this.issue_ list [index]; var comment = issue.comments [cindex]; axios.get ('comment/delete/cid/'+comment.cid) .then (function (resp) {issue.comments.splice (cindex,1);});}, saveComment: function (data) {var index = data.index; var comment = data.comment; var that = this Var issue = that.issue_ list.var data = {iid: issue.issue_id, content: comment}; axios.post ('comment/save/',data) .then (function (resp) {issue.comments=issue.comments | | []; issue.comments.push ({cid: resp.data, content: comment});}); / / clear comment input this.comment= ";}}
Note that the passing of a parameter is an object
In fact, there are more scenarios that require communication between components.
Officially recommended means of communication
Preferred use of Vuex
Use event bus: eventBus to allow components to communicate freely
For more information, see $dispatch and $broadcast replacement
These are all the contents of the article "how to achieve data interaction between parent and child components in vuejs". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.