父子組件之間的數(shù)據(jù)交互遵循:
props down - 子組件通過props接受父組件的數(shù)據(jù)
events up - 父組件監(jiān)聽子組件$emit的事件來操作數(shù)據(jù)
示例
子組件的點擊事件函數(shù)中$emit自定義事件
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 }}父組件監(jiān)聽事件
代碼如下:<comment v-show="issue.show_comments" :issue="issue" :index="index" @removeComment="removeComment" @saveComment="saveComment"></comment>
父組件的methods中定義了事件處理程序
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[index]; 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=""; } },注意參數(shù)的傳遞是一個對象
其實還有更多的場景需要組件間通信
官方推薦的通信方式
首選使用Vuex 使用事件總線:eventBus,允許組件自由交流 具體可見:$dispatch 和 $broadcast替換以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選