What is the best way to access the list value within a component?

Let's say I've imported a component called <pic-upload> into the template like this:

<template>
  <pic-upload></pic-upload>
</template>

export default {
  data: () => ({
    show: {
    content: '',
    recommend: false,
    albums: []
  }
}),
components: {
  picUpload
},
methods: {
  submit: function () {
    dataService.postpic(this.show).then(() => {
        this.$toast({
          message: 'success'
        })
      })
    }
  }
}

In the <pic-upload> component, it provides data and a method as follows:

// pic-upload component
export default {
  data () {
     return {
       imgList: []
     }
   },
  methods: {
     getUploadedImgList () {
       return this.imgList
     }
   }
 }

How can I access the value of imgList array in the template component so that I can send the data to the server?

Answer №1

If you're seeking to transfer data from a child component to a parent component, Vue.js follows the principle of props down, events up in the parent-child relationship. This means that the parent sends data down to the child through props, while the child communicates with the parent using events.

https://i.sstatic.net/I2Nka.png

For a practical example, refer to this documentation, where you can define a method in the parent component and call it from the child component using this.$emit().

In the parent component, create a method named saveLists:

<template>
  <pic-upload></pic-upload>
</template>

export default {
  data: () => ({
    show: {
    content: '',
    recommend: false,
    albums: []
  }
}),
components: {
  picUpload
},
methods: {
  submit: function () {
    dataService.postpic(this.show).then(() => {
        this.$toast({
          message: 'success'
        })
      })
    },
  saveLists: function () {
    //Code for saving 
    }
  }
}

To trigger this method from the child component, use $emit as shown below:

// pic-upload component
export default {
  data () {
     return {
       imgList: []
     }
   },
  methods: {
     getUploadedImgList () {
       return this.imgList
     },
     callParent () {
       this.$emit('saveLists')
     }
   }
 }

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

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...

Disappear the popup box when the document is clicked anywhere

My goal is to create a component that displays a list of items. When I click on an item, it should show an edit popup. Clicking on the item again should hide the edit popup. Additionally, I want to be able to click anywhere on the document to hide all edit ...

Reformat the numerical value and convert it into a numeric format

Utilizing both MUI and Formik libraries for form creation, I am in need of adjusting the number format in all input fields: 1000.00 -> 1.000,00 I developed a function named formatNumber(num) to achieve this transformation, which is successfully workin ...

What could be causing the entire app to malfunction when the Redux Provider tag is used

I am facing an issue while trying to integrate a React Toolkit app into my project. The error message I encountered is as follows: Error: Invalid hook call. Hooks can only be called inside the body of a function component. This error may occur due to one ...

Can you show me how to recreate a 502 gateway timeout error?

Looking for suggestions on how to create a page that exceeds 600 seconds to load? Any tips on triggering a 502 gateway timeout error would be helpful as well. ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

Uncover the hidden treasure within Vue.js

As a newcomer to Vue, I am still in the process of learning more about it. One challenge I am facing is trying to access and format the value of an item where decimal places and commas are involved. for (let j in data.table.items) { console.log(data.ta ...

Innovative method for inserting HTML content into the user's clipboard across multiple browsers

If Stackoverflow decided to implement a simple "Copy link to this question" feature. Upon clicking this link on What is your best programmer joke?, it would automatically copy the following HTML code to your clipboard: <a href="https://stackoverflow.co ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Techniques for navigating unidentified JSON structures using JavaScript

Currently, I am faced with the challenge of parsing the given data: { 'unknown-value': { name: 'AB', id: 'BLUE' }, 'unknown-value': { name: 'AC', id: 'PURPLE' } } My objec ...

Ways to display only a specific color in an image

Looking to work with an image that contains predefined color blocks? Take this example picture as reference: https://i.sstatic.net/QlwvY.png Is there a method to display only certain colored areas while keeping the rest transparent? Note that no edge pat ...

The structure becomes disrupted when the Material Ui grid is enclosed within a div container

I currently have a responsive dashboard built with Material Ui's Grid elements. One of the grid items is wrapped in a div element, causing the layout to break. Check out the playground with the div element here: https://codesandbox.io/s/basicgrid-mat ...

Disabling Commands using Discord JS Commando in a guild

Curious about something. Will Discord JS Commando disable a command only within a specific server (guild) or globally across all servers? ...

Adding Bootstrap 5 component to a create-react-app

Hello there! I appreciate any assistance with my Bootstrap 5 integration in a React app. I'm facing issues with including the Bootstrap component js, and below is the code snippet where I attempt to import it. import "bootstrap/dist/css/bootstrap ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Implementing a one-time watcher with user input in Vue.js

I am facing an issue with using the input tag in a Vue template. I need to change the type from 'password' to 'text'. <input type="text" v-model="form.password" /> To achieve this, I have created a watch code to convert text s ...

What is the process for testing promise functions that contain an internal promise using Jasmine in an Angular environment?

In my service function, here's how it looks: asyncGetStuff: (id) -> stuff = [] @asyncGetItem id .then (item) -> #parse some data stuff.push data return stuff Now I am trying to verify the contents of 'stuff': ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Obtain data from handlebars within a script tag

Is it possible to retrieve a handlebar parameter inside a script tag within a handlebars template? <script> var myList = {{list}} </script> This particular template is invoked from express using the following: response.render('t ...

The React application does not appear to update when there are changes made to a child Component

As a beginner in React, I have just started learning how to create a Todo list. Here is what I have so far: However, I am facing an issue where the count of remaining tasks does not update when I check off a task on the list, even though the 'checked ...