What is the best approach for updating data in a v-data-table dynamically?

I'm currently working on a node and electron application that utilizes vuetify to create a table (v-data-table) fetching data from an oracle database. The issue I'm facing is that even though the data changes based on the input value, the table fails to update!

Here's what happens when the input values change: process.env.ANO_SEM = input.val()

After this change, I trigger the loadData() function

Process.env.ANO_SEM serves as a parameter for the SQL query in the getEventos() function

This is my current code:


 $('#input').keyup(e => {
        if (e.keyCode == 13) {
            process.env.ANO_SEM = $('#input').val()
            loadData()
        }
 })

// Getting data from the Database
async function getEventos() {
    const sql = await fs
        .readFileSync(path.join(process.env.ROOT_PATH, 'src/db/sql/get-evento.sql'))
        .toString()
    return await db.getData(sql, [process.env.ANO_SEM])
}

async function loadData() {
    let data = await getEventos()
    console.log(data) // The data always changes, but the table never updates
    new Vue({
        el: '#app',
        methods: {
            rowClick(idEvento) {
                require(path.join(process.env.CTRL_PATH, './evento/evento-ctrl.js'))(
                    window.$,
                    idEvento
                )
            }
        },
        data: function() {
            return {
                selectedItem: 'Sample',
                pagination: {
                    sortBy: 'ID'
                },
                headers: [
                    { text: 'ID', value: 'ID', align: 'center', width: '10%' },
                    { text: 'Descrição', value: 'DESCRICAO', align: 'left', width: '60%' },
                    { text: 'Período', value: 'PERIODO', align: 'left', width: '20%' },
                    {
                        text: 'Data Impressão',
                        value: 'DATA_IMPRESSAO',
                        align: 'left',
                        width: '10%'
                    }
                ],
                eventos: data
            }
        }
    })
}

Here's my HTML code:

<div id="app" class="table-eventos">
        <v-app>
            <v-data-table
                :headers="headers"
                :items="eventos"
                :rows-per-page-items="[100]"
                item-key="name"
                class="elevation-1"
            >
                <!-- :pagination.sync="pagination" -->
                <template slot="items" slot-scope="props">
                    <tr @click="rowClick(props.item.ID)">
                        <td class="text-xs-left">{{ props.item.ID }}</td>
                        <td class="text-xs-left">{{ props.item.DESCRICAO }}</td>
                        <td class="text-xs-left">{{ props.item.PERIODO }}</td>
                        <td class="text-xs-left">{{ props.item.DATA_IMPRESSAO }}</td>
                    </tr>
                </template>
            </v-data-table>
        </v-app>
    </div>

Answer â„–1

Essentially, in your code, you're loading Vue into #app, which then renders and changes the appearance of your new #app element. However, despite being linked to the new Vue instance and rendered again, Vue fails to function properly.

In summary, it's recommended to place your render element within a static template that can be re-rendered effectively:

I've created a simplified example based on your initial code:

Vue.config.productionTip = false;
const mockData = Array.from({length: 100}, (_, i) => [{
      DATA_IMPRESSAO: `mock${i}`,
      PERIODO: `mock${i}`,
      DESCRICAO: `mock${i}`,
      ID: `mock${i}`,
  }])
  
  let nonReactiveIndex = Math.floor(Math.random()*mockData.length)
 setInterval(() =>
new Vue({
  template: "#example",
  vuetify: new Vuetify(),
  mounted() {
    nonReactiveIndex = Math.floor(Math.random()*mockData.length)
    console.log("mounted", nonReactiveIndex);
    
  },
  data() {
    return {
      headers: [
        { text: "ID", value: "ID", align: "center", width: "10%" },
        { text: "Descrição", value: "DESCRICAO", align: "left", width: "60%" },
        { text: "Período", value: "PERIODO", align: "left", width: "20%" },
        {
          text: "Data Impressão",
          value: "DATA_IMPRESSAO",
          align: "left",
          width: "10%"
        }
      ],
      eventos: mockData[nonReactiveIndex]
      
    };
  },
  
}
).$mount('#app'), 2000)
<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/font@latest/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>

    <div id="app" class="table-eventos">
      
    </div>
    
    <template id="example">
    <v-app>
        <v-data-table
          :headers="headers"
          :items="eventos"
          :rows-per-page-items="[100]"
          item-key="name"
          class="elevation-1"
        >
          <!-- :pagination.sync="pagination" -->
          <template slot="items" slot-scope="props">
            <tr @click="rowClick(props.item.ID)">
              <td class="text-xs-left">{{ props.item.ID }}</td>
              <td class="text-xs-left">{{ props.item.DESCRICAO }}</td>
              <td class="text-xs-left">{{ props.item.PERIODO }}</td>
              <td class="text-xs-left">{{ props.item.DATA_IMPRESSAO }}</td>
            </tr>
          </template>
        </v-data-table>
      </v-app>
    </template>


To enhance your design, consider encapsulating everything within the Vue component for improved reactivity management:

Vue.config.productionTip = false;
const mockData = Array.from({length: 100}, (_, i) => [{
      DATA_IMPRESSAO: `mock${i}`,
      PERIODO: `mock${i}`,
      DESCRICAO: `mock${i}`,
      ID: `mock${i}`,
  }])
  

new Vue({
  template: "#example",
  vuetify: new Vuetify(),
  mounted() {
    
    console.log("mounted", this.reactiveIndex);
    
  },
  data() {
    return {
      reactiveIndex : Math.floor(Math.random()*mockData.length),
      headers: [
        { text: "ID", value: "ID", align: "center", width: "10%" },
        { text: "Descrição", value: "DESCRICAO", align: "left", width: "60%" },
        { text: "Período", value: "PERIODO", align: "left", width: "20%" },
        {
          text: "Data Impressão",
          value: "DATA_IMPRESSAO",
          align: "left",
          width: "10%"
        }
      ],
     
      
    };
  },
  computed: {
      eventos(){ return mockData[this.reactiveIndex] }
  },
  methods: {
    load(){
      this.reactiveIndex = Math.floor(Math.random()*mockData.length)
      console.log(this.reactiveIndex)
    }
  }
}
).$mount('#app')
<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/font@latest/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>

    <div id="app" class="table-eventos">
      
    </div>
    
    <template id="example">
    <v-app>
        <v-btn @click="load">load</v-btn>
        
        <v-data-table
          :headers="headers"
          :items="eventos"
          :rows-per-page-items="[100]"
          item-key="name"
          class="elevation-1"
        >
          <!-- :pagination.sync="pagination" -->
          <template slot="items" slot-scope="props">
            <tr @click="rowClick(props.item.ID)">
              <td class="text-xs-left">{{ props.item.ID }}</td>
              <td class="text-xs-left">{{ props.item.DESCRICAO }}</td>
              <td class="text-xs-left">{{ props.item.PERIODO }}</td>
              <td class="text-xs-left">{{ props.item.DATA_IMPRESSAO }}</td>
            </tr>
          </template>
        </v-data-table>
      </v-app>
    </template>

Answer â„–2

I took the initiative to organize the project structure using vue-cli and included mock data along with a text-field. Feel free to reach out if you have any questions - I'm confident you'll grasp the concept. Simply clone the public repository, execute the following commands:

 npm install

and then

npm run serve

https://github.com/sdpotts93/vue-simple-table

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

Obtaining the value of cookies in express js is a simple task that

Is there a way to retrieve the value of a cookie? const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.get('/', (req, res) => { res.setHeader('Set-Cookie', 'Cookie=HELLO'); }); I' ...

The error message 'Blob is undefined' pops up when trying to use react-media-recorder in an Astro project

I'm currently working on a project that involves Astro and React components, and I'm attempting to integrate react-media-recorder. The code I have is quite simple, just a React component placed within an Astro page: import { useReactMediaRecorde ...

Dynamic TextField sizing

I am currently facing an issue while displaying data on a webpage using TextField component from @material-ui. Each record of data has varying lengths, making most values appear unattractive (occupying only 10% of the textfield width). Even though I am ut ...

Transferring information to a partial view using a jQuery click event

In my Index view, there is a list of links each with an ID. My goal is to have a jQueryUI dialog box open and display the ID when one of these links is clicked. Currently, I am attempting to use a partial view for the content of the dialog box in order to ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Nodejs registration and user verification process for accessing account features

I am facing a decision on how to handle two types of users - vendors and buyers. Should I develop separate APIs for registering and authenticating each user type, or should I create a single API to manage both? When designing my database model, should I h ...

What is the best way to align text extracted from an API using JavaScript?

I'm currently exploring content generation through APIs, but I'm facing an issue where the text generated is not aligning properly within the container on the screen. The main problem lies in getting the card to be centered on the screen with al ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

The identifier '_toConsumableArray' has been declared beforehand

Whenever I try to start my Redux app, I encounter the following issue: ./node_modules/draftjs-md-converter/dist/index.js Syntax error: /Users/vlasenkona/Desktop/gris-seqr2/ui/node_modules/draftjs-md-converter/dist/index.js: Identifier '_toConsumableA ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

The fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

Guide to implementing vue i18n $t method in vuex getters for vue 3

How do I incorporate i18n $t into my getters to retrieve a static label? I attempted importing it in the following way: import { i18n } from '../../locales/i18n.js'; const getters = { guaranteePolicies: state => { let guaranteesS ...

Personalize the appearance of your stackLabels in Highcharts with dynamic customization options

I recently created a bar graph using Highcharts. You can check it out here: http://jsfiddle.net/v1rbz41q/3/ Here's the code snippet I used: chartw.yAxis [0] .options.stackLabels.formatter = function () {              return "werfdc";   ...

What is the best method in Selenium IDE for tracking an element based on its value?

While testing a website with Selenium IDE, I encountered an issue with the way elements are identified. The site utilizes something called "wickets" that change the ID of elements randomly, making it difficult for Selenium to record actions on certain elem ...