1
votes

I am wondering how I take an existing (initial) v-data-table component whose :headers and :items props are populated, and then completely re-render the component with new data and new column headers? Is there a special update or destroy native Vue or Vuetify way to do this?

I want my UX to be: See initial table that is created on mount, choose new columns, click update, queue loader icon, table is re-rendered with new items and new headers.

Thanks in advance.

1
What solution have you tried so far?Adam Orlov
Stop wondering and start coding. Your question shows unequivocally you haven't yet tried anything. In short, as long as your items and headers are reactive, any change to them will trigger a re-render, accordingly. For the human eye, it's instant, so if you want to see a loader icon you'll need to display the loading icon before you perform the update, display it for as much as you think the update process should take and then hide it, updating the data.tao

1 Answers

0
votes

VDataTable is driven by the data you feed to it through headers & items. If the sources change, the table changes. So, don't do anything else, just update the sources (in a reactive way) & your table is going to update according the new set of data fed to it.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  computed: {
    headers() {
      return this.items.length ? Object.keys(this.items[0]).map(key => ({
        value: key,
        text: key
      })) : []
    }
  },
  data() {
    return {
      items: []
    }
  },
  methods: {
    async fetchData(type) {
      const response = await fetch(`https://jsonplaceholder.typicode.com/${type}`)
      this.items = await response.json()
      console.log(this.items)
    },
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-row>
          <v-col>
            <v-btn-toggle>
              <v-btn @click="fetchData('users')">
                FETCH USERS
              </v-btn>
              <v-btn @click="fetchData('posts')">
                FETCH POSTS
              </v-btn>
            </v-btn-toggle>
          </v-col>
        </v-row>
        <v-row>
          <v-col>
            <v-data-table :headers="headers" :items="items" />
          </v-col>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</div>