Vue.js causing issues with jQuery data table

Utilizing jQuery data-table within Vue.js in a laravel project has presented an issue for me. Although the data loads successfully into the data-table, there seems to be a problem with retrieving the data after it has been loaded. Specifically, the first row in the data-table displays "there is not any data" even though there should be data present. What steps can I take to effectively use jQuery data-table in conjunction with Vue.js?

Below is a snippet from my app.js file:

const platform = {
    el: '#platform',

    data: {
        name: '',
        platforms: [],
    },

    methods: {
        index() {
            axios.get('/api/platforms', {
                headers: headers
            }).then(response => {
                this.platforms = response.data.data;
                this.dataTable.row.add([
                    this.platforms
                ]);
            }).catch(error => {
                alert(error.response.data.message);
            })
        },

        store() {
            axios.post('/api/platforms', {
                params: {
                    name: this.name
                }
            }, {
                headers: headers
            }).then(response => {
                this.platforms.push(response.data.data);
                alert(response.data.message);
            }).catch(error => {
                if (error.response.status === 422) {
                    this.message = error.response.data.data['validation-errors']['params.name'];
                } else {
                    this.message = error.response.data.message;
                }
            })
        },
    },

    mounted() {
        this.index();
    },
};

Additionally, here is a segment from the platform.blade.php file:

<section class="content" id="platform">
  <div class="form-group">
      <input type="text" v-model="name">
   </div>
   <button class="btn btn-raised" @click.prevent="store()">save</button>

   <div class="row">
     <table class="table table-bordered table-striped table-hover dataTable">
       <thead>
         <tr>
           <th>platform name</th>
         </tr>
         </thead>
          <tbody>
            <tr v-for="(platform, index) in platforms">
             <td>{{ platform.name }}</td>
            </tr>
          </tbody>
      </table>
   </div>
</section>

Answer №1

When working with Reactivity, it is important to initialize the platforms property within the data() section. This allows Vue to set up all necessary getters and setters automatically.

Additionally, whenever updating the this.platforms property with a response from an API call, make sure to assign a new array reference to ensure proper reactivity.

data: {
    name:'',
    platforms: []
},

...
index:function() {
        axios.get('/api/platforms', {
            ...
        }).then(response => {

            // update 'this.platforms' with a new array reference
            this.platforms = [ ...response.data.data];
            ...
        }).catch(...)
    },

...
store:function() {
        axios.post('/api/platforms', 
          ...
          ...
        ).then(response => {

           // update 'this.platforms' with a new array reference
           this.platforms = [...response.data.data];
            alert(response.data.message);
        }).catch(...)
    }
},

...

Answer №2

ES6 offers a solution for this situation...
`

  <div class="row">
   <table class="table table-bordered table-striped table-hover dataTable">
    <thead>
     <tr>
       <th>platform name</th>
     </tr>
     </thead>
      <tbody>
        <tr v-for="(platform, index) in platforms">
         <td>@{{ platform.name }}</td>
        </tr>
      </tbody>
   </table>
  </div>
 </section>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
 name: "App",
 data(){
   return{
      name:'',
      platforms: [],
   }
 },
 methods: {
    index:function() {
        axios.get('/api/platforms', {
            headers: headers
        }).then(response => {
            this.platforms = response.data.data;
            this.dataTable.row.add([
                this.platforms
            ]);
        }).catch(error => {
            alert(error.response.data.message);
        })
    },

    store:function() {
        axios.post('/api/platforms', {
            params: {
                name: this.name
            }
        }, {
            headers: headers
        }).then(response => {
            this.platforms.push(response.data.data);
            alert(response.data.message);
        }).catch(error => {
            if (error.response.status === 422) {
                this.message = error.response.data.data['validation-errors'] 
                 ['params.name'];
            } else {
                this.message = error.response.data.message;
            }
        })
    },
},
mounted:function() {
    this.index();
},
components: {
  HelloWorld
}
};
</script>`

An issue arises in the mounted hook: "ReferenceError: axios is not defined." This error may occur....ESLINT must be installed and the axis method needs to be defined.

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

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

How to refresh the javascript cache in Laravel 5.8

I developed a company profile website using Laravel 5.8 and Vue.js to make it reactive, although it's not a single page application (SPA), we can refer to it as a hybrid. The website runs smoothly locally; however, after modifying the JavaScript code ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Adding automatic hyphens in dates within React

My goal is to create a date field in React, similar to the one on this page, with the date format of yyyy/mm/dd. This is my current approach: const [date_of_birth,setDateofBirth] = useState(""); const handleChangeDOB = (e) => { let value = e.target ...

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

Are XHR2 credential requests truly secure or easily faked?

I am working to determine the level of security provided by credentialed XHR2 requests. More precisely, can I verify that the request originated from a browser runtime environment, and not from a bot (such as a server-side program) that might be able to m ...

Gulp is showing an error of "Module Not Found" despite the module being present in the project

I've come across an unexpected issue and I'm at a loss for solutions. As part of my exploration into JS unit testing, I am configuring gulp with Jasmine. However, when I run my gulp build, I encounter the following error: Error: Cannot find modu ...

A TypeError was encountered: Attempting to read the 'substr' property of an undefined variable

Recently, I encountered an issue while working on a script with jquery.min.js version 1.4. The problem arose when I had to upgrade the script to version 1.9.1. Uncaught TypeError: Can not read property 'substr' of undefined. I need assistance i ...

Trouble encountered while setting up Firebase Auth for React Native by utilizing AsyncStorage

Trying to implement SMS authentication via Firebase has presented some challenges for me. Despite poring over the documentation and scouring Google for solutions, I've hit a dead end. My setup is pretty basic - just a single input field and a "Send" b ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:

export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'Shared& ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

React does not allow objects as children, but what if it's actually an array?

My function is encountering an error message that reads: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead." I am struggling to understand why this error is occurring. ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...