View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The button has an @click function called

@click="searchRegisters()">
which triggers the searchRegister function. This function in turn calls an anonymous function within a composable that utilizes axios to perform a POST request and fetch data. Here is a snippet of the returned data:

{"data":[{"id":895,"name":"Aguilera Muriel Fatimas","address":"CALLE CALLEJAS, 8"

While my composable and function calls seem to be working fine, I am facing difficulties displaying the fetched data in my component named nAsignedCalls. To pass the data to this component, I use the searchRegister function that emits the data like this:

context.emit("registers", getRegisters(toRef(param_search,'param_search')))

In my setup(), I have defined a custom emit method as follows:

const emitMyEvent = (event) => emit('registers', event);

The getRegisters function within the composable returns the fetched data:

const getRegisters = async (param_search) => {
        var keys = Object.values(param_search);

        var formData = new FormData();
        formData.append("parameter", keys[0].parameter);
        formData.append("value", keys[0].value);
        let response = await axios.post('/api/listingApi/getRegister', formData, {'content-type': 'multipart/form-data'}) 
        registers.value = response.data.data
    } 

In the component nAsignedCalls, while defining it with export default defineComponent, I specify that it emits the 'registers' event:

emits: ['registers']

Furthermore, I return various functions and values related to the data handling:

return { 
       remove,
       searchId,
       searchName,
       searchPhone,
       edit,
       getResults,
       getPage,
       emitMyEvent,
       getRegisters,
       registers,
 }

To display the data in my template, I use a v-for loop to construct the table body:

<tbody>
            <template v-for="item of registers"> 
                <tr>
                    <td>{{ item.id }}</td>
                    ...
                    // Remaining code omitted for brevity
                </tr>
            </template>
        </tbody>

Despite successfully fetching the data in the network tab, I'm struggling to display it in the table or pass it correctly. I am relatively new to Vue.js 3 and still learning from extensive documentation.

UPDATE

I noticed that when assigning the result to my ref variable, a promise is obtained. So, I added the following then() function to handle this:

getRegisters(toRef(param_search,'param_search')).then(response => this.register_data = response)
console.log(this.register_data)

However, the console now shows a blank output. Any guidance or help will be greatly appreciated. Apologies for any language errors in my message.

Answer №1

If your goal is to simply fetch data and display it in a table, then there's no need for any additional events.

UPDATE

It doesn't matter where your data resides. Whether it's in a composable or Pinia store, you can access it easily.

Here's a simple example:

const { createApp, ref, onMounted } = Vue 

const useStore = () => {
  const posts = ref([])
  const getData = () => {
    posts.value = []
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((data) =>  posts.value = data)
  }   
  return { posts, getData }
}

const Blog = {
  props: ['posts'],
  template: '#blog'
}

const App = {
  components: { Blog },
  setup() {    
    const { posts, getData } = useStore()    
    onMounted( () => getData());
    return { posts, getData }  
  }
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
label { font-weight: bold; }
<div id="app" v-cloak>
<button @click="getData()">reload</button><br/>
<blog :posts="posts"></blog>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="blog">
<div v-for="post in posts" :key="post.id">
  <label>Id:</label>&nbsp; {{post.id}}<br/>
  <label>Title:</label>&nbsp; {{post.title}}<br/>
  <label>Body:</label>&nbsp; {{post.body}}<br/>
  <hr/>
</div>
</script>

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

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

Is it possible to verify the presence of the "#" tag within a string?

As a novice in node.js, I appreciate your patience with my question. We are aware that we can use var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g; regex.test(str); to verify if a string contains special ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL: http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br> I am utilizing ajax jsonp for this task. Below is the complete code snippet ...

Changing the visual appearance of an alert in JavaScript and HTML

My knowledge in JavaScript is limited, but I have a script that retrieves a query from a Python service to a Mongodb database. The query is returned in the following format: [{CHAIN: "STREET ELM, ELMER", CODE: "1234"}, {CHAIN: "STREET LM, LMAO", CODE: ...

Update and change the property based on a condition in Ramda without the need for a lens

I am looking to modify properties for an object in ramda.js without using lenses. Given the data provided, I need to: If objects in array properties in a and b do not have the property "animationTimingFunction", then add the property key "easing" with a ...

What is the best way to respond to a hashchange event within AngularJs?

I am new to AngularJs and I am trying to update the page on hashchange events. Currently, I have this code which I know is not the proper way to do it: <!DOCTYPE html> <html> <head> <style> #hashdrop { display:block; ...

Mounting Vue.js 3 component instances during execution time

I'm currently experimenting with vue-leaflet/vue-leaflet and I want to have multiple instances of <l-polyline> within the <l-map> component. However, I am unsure how to achieve this. Initial version (map displaying a pre-drawn polyline): ...

Utilizing ASCX to trigger JavaScript functions within an ASPX page

I created a user control named MyListSelect.ascx that contains a list of radio buttons... <%@ Control Language="C#" %> <select> <option disabled selected>Select Options</option> <option> option 1 </opti ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Hover over two different divs with JQuery

I have a situation where I have two HTML table rows. When I hover over the first row, I want to display the second row. However, once the mouse leaves both rows, the second row should be hidden. Is there a way to achieve this using JQuery? <tr class=" ...

Are the JQuery appended elements exceeding the width of the parent div?

I have an HTML div that is styled using the Bootstrap class span9. <div class="span9"> <div id = "selectedtags" class="well"> </div> <button class="btn" type="button" id="delegatecontent">Generate report</button&g ...

Guide to making Bootstrap collapsible panels with full-width content that do not affect neighboring columns

I'm currently working on a responsive grid that displays items with expandable details when clicked. My issue is that when one item expands, the elements next to it collapse down, which is not what I want. I want all items to stay at the top and have ...

Troubleshooting: Bootstrap 5 Submenu Dropdown Fails to Expand

I am struggling with implementing a dropdown menu in Bootstrap 5. Although the dropdown menu is visible, I am facing an issue where the submenu items do not expand upon clicking. Below is the code snippet that I am using: <body> <nav class=&qu ...

Enhancing Bootstrap Carousel with various effects

My exploration of the web revealed two distinct effects that can be applied to Bootstrap Carousel: Slide and Fade. I'm curious if there are any other unique effects, such as splitting the picture into small 3D boxes that rotate to change the image? ...

The initialization of the R Shiny HTML canvas does not occur until the page is resized

I am currently facing an issue while integrating an HTML page with a canvas into my shiny R application using includeHTML(). The packages I am using are shiny, shinydashboard, shinycssloaders, dplyr, and DT. Everything is working perfectly fine except for ...

Load data onto a dropdown menu using Ajax requests

My view currently includes a dropdown menu. Upon selecting an item from the dropdown, AJAX is supposed to load. The table 'locations' has a one-to-many relationship with 'contacts.' When I select a location from the locations dropdown, ...

Sending DOM values to React components as properties

Forgive me if this question seems basic, as I am still learning ReactJs. I have a react component that displays the user's sign-in status: <AccountStatus iconsize="medium" activate={[true,false,true]}/> Image 1 //or using <AccountStatus i ...