vuejs中怎么实现父子组件间数据交互

今天就跟大家聊聊有关vuejs中怎么实现父子组件间数据交互,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

父子组件之间的数据交互遵循:

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,允许组件*交流

  • 具体可见:$dispatch 和 $broadcast替换

看完上述内容,你们对vuejs中怎么实现父子组件间数据交互有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。