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

Locate every item that has a value that is not defined

My data is stored in indexeddb, with an index on a text property of the objects. I am trying to retrieve all objects where this property's value is undefined. I have been experimenting with IDBKeyRange.only(key), but when I use null, undefined, or an ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Exploring the capabilities of Laravel Webpack Mix and harnessing the power of the

I'm curious about integrating Laravel Webpack Mix with version 5.8 of Laravel. Do I have to include Vue/jQuery in app.js using the extract method in Webpack Mix? Will this result in duplication when loading manifest.js/vendor.js/app.js ? ...

What is the best method to customize CSS in ExtJS 5.0 by overriding a function?

Is there a way to dynamically add a rule to existing CSS using code, particularly in overrides? For example: var sheets = document.styleSheets; // Some code omitted for simplicity var sheet = sheets[sheets.length - 1]; sheet.insertRule('.overlay {flo ...

Retrieving JSON data and showcasing it in HTML components

I'm attempting to retrieve JSON responses and showcase them within my predetermined HTML elements. I'm utilizing graphql from datocms. The API explorer displays the following for my model: query MyQuery { allNews { id newsTitle new ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

Struggling to understand the implementation of webpack's require.context() method

I'm currently working on an AngularJS project with webpack, and I'm looking for a way to import all the .js files in my project into webpack without manually adding each file path. Upon reviewing the webpack documentation, I came across the requi ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

Is it possible to turn off Vue warnings for a particular component?

In my Vue application, I have a parent component that includes its own on-screen keyboard, which is a separate Vue component. This keyboard tracks the entered value and sends it to the parent component. Sometimes, the parent component needs to reset this v ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

In what ways can I enhance and visually improve JSON data using a jquery/javascript plugin?

My current project requires me to display JSON data received from the backend in a textarea. However, the data comes unformatted and not validated. Now I'm facing two main challenges: 1) How can I beautify the JSON content in the textarea? 2) How can ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side. Below is my Java code snippet: byte[] kd = key.getByt ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Data structure designed specifically for a drawing tool application

Currently, I am in the process of developing a unique sketching application using the HTML5 Canvas element. Despite my progress, there is one particular challenge that has stumped me. The main concept of the application involves allowing users to manipula ...

Using identical content in various template slots

Is it possible in vuejs to assign the same content to multiple slots without repeating it? For example: <base-layout> <template slot="option"> <span :class="'flag-icon-' props.option.toLowerCase()" />{{ countriesByCode ...

Incorporate SCSS variables directly into Vue single component files for easy reuse

My goal is to package a repository in npm that holds a directory of Vue single file components, which can be easily imported like so: import { Button } from "@user/design-system" The issue at hand is that the Button.vue file contains variables sourced fr ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...