Establishing data using Vue.js

Apologies for my beginner question, but I have been struggling with a basic issue since yesterday and can't seem to find the solution.

I am trying to populate my logs variable with a JSON object and display it in an array.

Below is my HTML code :

<tbody>

  <tr v-for="log in logs">
    <td>{{log.incident}}</td>
    <td>{{log.request}}</td>
    <td>{{log.requested}}</td>
    <td>{{log.message}}</td>               
  </tr>            

</tbody>

And here is my JavaScript code:

let vm = new Vue({
    el: '#container',
    components: {
        'table-header': tableHeader,
    },
    data: {
        logs: []
    },
    methods: {
        getLogs() {
            addon.port.on('log', function (data) {
               console.log(data);
               this.$add('logs',data)
            });
        }
    },
    ready:{
        function(){this.getLogs()}
    }

});

vm.getLogs();
  1. The "ready" function doesn't appear to be working. Any idea why?
  2. Why is this.logs returning as undefined?
  3. It's showing an error that "this.$add is not a function". Why is that?
  4. Despite the code, the logs aren't populating in the loop in the HTML. What could be causing this issue?

Answer №1

  1. Make sure your ready function is a function, not an object.

2&3&4. When using an anonymous function, the context of 'this' may change. Use an arrow function to maintain the scope of 'this', or store a reference to it.

let vm = new Vue({
     el: '#container',
     components: {
         'table-header': tableHeader,
     },
     data: {
         logs: []
     },
     methods: {
         getLogs() {
             addon.port.on('log', (data) => {
                console.log(data);
                this.$add('logs',data)
             });
         }
     },
     ready() {
         this.getLogs()
     }

     });

//OR do this
getLogs() {
  var that = this;
             addon.port.on('log', function(data) {
                console.log(data);
                that.$add('logs',data)
             });
         }

Answer №2

You could opt to utilize the mounted hook in this manner:

mounted () {
    this.getLogs()    
}

Check the official documentation for more information.


The data must be a function requirement applies to Vue components, while for a Vue instance it is not necessary.

Therefore, for a Vue component, the data should be structured as follows:

data: function () {
  return {
    logs : []
  }
}

Answer №3

I'm not sure if your example is actually valid, and unfortunately I can't test it right now. Typically, the syntax I am familiar with looks like this:

ready: function(){
    console.log('ready);
}

The same applies to your methods. It might be helpful to consult the documentation and follow the suggested syntax provided there.

https://vuejs.org/guide/index.html#Getting-Started

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

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Encountering the below error message when running the command to initialize expo project:

Dependency installation in progress... Warning: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="accfc3dec981c6dfec9d829e829b">[email protected]</a> is deprecated, consider upgrading to core-js@3 or a ne ...

Troubleshooting parameter issues with Vue Router on page refresh

Why does the parameter work when I'm directed from a `router-link' to a component, but then not work when I refresh the page? Let me explain: routes.js has the following paths: { path: '/myspaces', name: 'myspaces', ...

Invoke the parent function when extending javascript prototype

Below is the Meta-Code I am currently working with: var Parent = function(){} Parent.prototype.doSomething = function(){ console.log("As a parent I did like a parent"); } var Child = function(){} Child.prototype = new Parent(); Child.prototype.doSometh ...

Having trouble with input event listeners in JavaScript?

I've been attempting to trigger the keyup event using EventListener for an input tag, but it doesn't seem to be working and I'm unsure why. Here is the code I have: document.getElementById("ajax").addEventListener("keyup", function() { ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

Passing Data from Child to Parent Components in ReactJS

I'm new to React and JavaScript, currently working on a website. I've encountered an issue with passing data between components from child to parent. Here's the scenario: In my App.js script, I'm using react-router-dom for routing. I ...

Is there a way for me to display the output from Firebase on the html template when the page first loads?

I am currently in the process of building a blog post page using VueJs. Here is my template: <template> ... <q-item-section> <q-item-label class="text-subtitle1"> <strong>Danny Co ...

Send a PHP array back to jQuery AJAX and dynamically populate a list using conditional statements

Looking to create a dynamic contact list that can be sorted using AJAX. When selecting one of the 3 menu options, a new list with updated information should be displayed. I've been doing some research but haven't come across useful information o ...

Dragging an image in KineticJS gets stuck after the drag operation is completed

My experience with KineticJS has been positive so far, but I have encountered an issue with dragging images. In the example below, I have set the image to be draggable, but after the initial drag, it seems like the image can't be moved again. var sta ...

What is the purpose of enveloping the BrowserRouter in a parent component as opposed to the routes child component for react router v6?

Attempting to implement the useRoutes hook from [email protected] for creating App routes in JavaScript, I organized my code as follows in routes.jsx: import { useRoutes } from "react-router-dom"; import TestPage from "../Pages/Public/T ...

Information is being received, but unfortunately, it cannot be displayed

Currently, I am experimenting with using the axios http request to showcase some data. My focus is on exploring how to exhibit api data on the client side with react. If you are interested in seeing my progress so far, feel free to check out the link belo ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Transfer the HTML5 FullScreen (MAP) feature onto a separate display

I'm trying to integrate a leaflet map into my AngularJS Application, but I've hit a roadblock. My goal is to move the Fullscreen feature of the Map to a second screen (if one is available), allowing users to interact with the application on the ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Text Overlapping Issue in React Material UI Components

I am currently working on a React application using Material UI and facing an issue while implementing an entity update page. The task at hand is to display the existing values of the entity for the user to update. To achieve this, I have set the default v ...

The key property is present on the list item, yet the key warning persists

I have encountered various issues with this problem, but I am unable to pinpoint the exact cause. I am not extracting individual list items and simply displaying a UL with unique keys assigned to each item. However, when I log the results, I see something ...

Simulated script in a different component

I am looking to simulate the functionality of Amazon AWS S3 getObject The specific code I aim to test is located in helper.js var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.get_data_and_callback = function(callback, extra){ s3. ...

What is the process for determining the vertex position of geometry in three.js after applying translate, rotate, and scale transformations?

I've recently delved into the world of three.js. My current goal involves creating a curve within the scene and subsequently applying some transformations to it. The function responsible for generating the line is showcased below: var random_degree ...