首页 > 解决方案 > VueJS - 如何从另一个组件刷新表格组件?

问题描述

我有两个 Vue 组件:一个是表单,另一个是表格,它们在同一页面中。我想在提交表单时用新值刷新表格。

为了做到这一点,我需要调用从表单组件中获取数据并将其显示在表格上的函数,所以我需要跨两个不同的组件调用一个函数,我这样做了并且它可以工作。

问题是,虽然我可以从表单组件调用另一个组件中的函数,但表格不会用新值刷新,我该如何解决这个问题?

这是我的代码:

表单组件:

<template>
...
</template>

<script>

import axios from 'axios'

    export default {

      props:{

        order:{
          type:String, 
          default:'data'
        },

      },

      mounted() {
          console.log('Component mounted.')
      },

      data() {
          return {
            name: '',
            description: '',
            output: ''
          };
      },
      methods: {
          formSubmit(e) {
              e.preventDefault();
              console.log('Called fetchData!')
              let currentObj = this;
              axios.post('MYURL', {
                'add_data': data, 

              })
              .then(function (response) {
                  this.fetchData()
                  currentObj.output = response.data;
              })
              .catch(function (error) {
                  currentObj.output = error;
              });
          }

          fetchData: function(){
           this.$root.$emit('table_component')
          },
      }
    }

</script>

表格组件:

<template>

  <v-data-table 
    :headers="headers"
    :items="customers"
    :items-per-page="5"
    :hide-default-footer="true"
    class="elevation-1"
  >

  </v-data-table>
</v-container>
</template>

<script>

import axios from 'axios';

export default {
 
  data() {
    return {

      search: '',

      headers: [
        { text: 'Name', value: 'Name' },
        { text: 'Item', value: 'Item' },
      ],

        customers: [],
    }
  },

  mounted() {
    this.fetchData()

    this.$root.$on('table_component', () => {
            this.fetchData()
    },

  },

  methods: {
    fetchData() {
      fetch('MYURL')
        .then(response => response.json())
        .then(data => {
          console.log(data)
          this.customers = data;
        })
    },

  }
}

</script>

这是我在这段代码中所做的:当提交表单并收到响应时,我调用函数fetchData()。调用该函数是因为我看到console.log('Called fetchData!')被触发了,所以它起作用了,唯一不起作用的是表没有用新值刷新。任何建议表示赞赏!

标签: vue.js

解决方案


似乎您在 then 函数中的上下文有问题

formSubmit(e) {
  e.preventDefault();
  console.log('Called fetchData!')
  let currentObj = this;
  axios.post('MYURL', {
    'add_data': data, 
  })
    .then((response) => {
      this.fetchData()
      currentObj.output = response.data;
    })
    .catch(function (error) {
      currentObj.output = error;
    });
}

您可以使用如上所示的箭头函数来调用 this.fetchData

或者你可以使用绑定

formSubmit(e) {
  e.preventDefault();
  console.log('Called fetchData!')
  let currentObj = this;
  axios.post('MYURL', {
    'add_data': data, 
  })
    .then(function (response) {
      this.fetchData()
      currentObj.output = response.data;
    }.bind(this))
    .catch(function (error) {
      currentObj.output = error;
    });
}

推荐阅读