vuejs组件交互 - 01 - 父子组件之间的数据交互
2017-08-09 08:16
801 查看
父子组件之间的数据交互遵循:
props down - 子组件通过props接受父组件的数据
events up - 父组件监听子组件$emit的事件来操作数据
父组件监听事件
父组件的methods中定义了事件处理程序
注意多参数的传递是一个对象
首选使用Vuex
使用事件总线:eventBus,允许组件自由交流
具体可见:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替换
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 } }
父组件监听事件
<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=""; } },
注意多参数的传递是一个对象
其实还有更多的场景需要组件间通信
官方推荐的通信方式首选使用Vuex
使用事件总线:eventBus,允许组件自由交流
具体可见:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替换
相关文章推荐
- vuejs父子组件之间数据交互详解
- vue.js---父子组件之间简单的数据传递
- vue.js 组件之间传递数据
- 关于vue.js父子组件数据传递
- vue.js组件之间通讯的数据双向绑定----父亲把数据传递给儿子,儿子更改数据后,重新发送给父亲,父亲数据更改后,属性会重新发送个儿子,儿子刷新新数据
- vue.js使用props在父子组件之间传参
- Vue2.0子同级组件之间数据交互方法
- vue.js组件之间传递数据的方法
- vue.js实战笔记:父子组件之间的那些事儿
- vue.js通过子组件通信和父子组件通信实现动态表单动态绑定事件(适合交互系统统一使用)
- Vue.js实战之组件之间的数据传递
- vue.js 组件之间传递数据
- vue.js组件之间的通讯-----父亲向儿子传递数据,儿子接收父亲的数据
- vue.js $refs和$emit 父子组件交互的方法
- Vue2.0子同级组件之间数据交互
- vue 父子组件之间的数据传递
- vue.js 组件之间传递数据
- vue.js $refs和$emit 父子组件交互
- vue.js 组件之间传递数据
- vue.js使用props在父子组件之间传参