How can I get the list value in a component?

247 views Asked by At

For example, I have import a component named <pic-upload> in the template, like

<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'
        })
      })
    }
  }
}

and in the <pic-upload> component, it returns data and a method like:

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

so how can I get the value of imgList array in the template component which I can post the data to the server?

1

There are 1 answers

0
Saurabh On BEST ANSWER

What you are looking for is sending data from a child to parent. In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

enter image description here

You can have a look at the example here, you can define a methods in the parent component and invoke that from child component using this.$emit().

You can define a method saveLists in parent component:

<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 to save 
    }
  }
}

Then you can trigger this method using $emit from child component like following:

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