父子組件之間的數據交互遵循:
props down - 子組件通過props接受父組件的數據
events up - 父組件監聽子組件$emit的事件來操作數據
示例
子組件的點擊事件函數中$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 }}父組件監聽事件
父組件的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=""; } },注意參數的傳遞是一個對象
其實還有更多的場景需要組件間通信
官方推薦的通信方式
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答