vue-transmit-data-in-comp

Transfer data from child component to parent

HTML

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui/lib/index.js"></script>
<div id="app">
  <son-item :table-data="tableData" @change-params="handelChangeParams" :callback="handelChangeParams" ref="sonitem"></son-item>

  <p class="gap-space"></p>
  <el-button type="success" size="small" class="btn-width" @click.prevent="onCallChildFuncClick">Call Child Function To Update</el-button>

  <script type="x-template" id="son-item">
    <div class="son-root">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="date" label="Date" width="180">
        </el-table-column>
        <el-table-column prop="name" label="Name" width="180">
        </el-table-column>
        <el-table-column prop="address" label="Address">
        </el-table-column>
      </el-table>

      <p class="gap-space"></p>

      <!-- Update data through parent component method  -->
      <p class="gap-space"></p>
      <el-button type="success" size="small" class="btn-width" @click.prevent="onTransferDataClick">Transfer data to parent comp</el-button>
      <el-tag type="success">Not Any Warn</el-tag>
      <el-tag type="gray">Update data through parent component method</el-tag>
    </div>
  </script>
</div>

CSS

@import url("//unpkg.com/element-ui/lib/theme-default/index.css");
.gap-space {
  margin: 15px auto;
}

.btn-width {
  width: 200px;
}

JavaScript

Vue.component('son-item', Vue.extend({
  template: '#son-item',
  props: {
    tableData: Array,
    callback: Function
  },
  data() {
    return {
      tableArr: this.tableData.slice()
    }
  },
  computed: {
    testArr: function() {
      console.log(this.tableData)
      return this.tableData.slice()
    }
  },
  methods: {
    onTransferDataClick() {
      this.tableArr.pop()
      console.log(this.tableArr)
      //this.$emit('change-params', this.tableArr)
      this.callback && this.callback(this.tableArr)
    },
    
    getUpdatedChildData() {
    	console.log('@child func updateChildData')
      this.tableArr.pop()
    	return this.tableArr
    }
  }
}));

new Vue({
  el: '#app',
  data() {
    return {
      tableData: [{
        date: '2016-05-02',
        name: 'Jade',
        address: 'China'
      }, {
        date: '2016-05-04',
        name: 'Rayso',
        address: 'Cambridge'
      }, {
        date: '2016-05-01',
        name: 'Scarlett',
        address: 'New York'
      }]
    }
  },
  methods: {
    handelChangeParams(params) {
      console.log('@parent handelChangeParams Func')
      console.log(params)
      this.tableData = params
    },
    
    // 当然这样子做,没什么意义,只是举例可以如此Hack,但尽可能不要这般去破坏设计的合理性。
    onCallChildFuncClick () {
    	this.tableData = this.$refs.sonitem.getUpdatedChildData()
    }
  }
});