How can I get the list value in a component?

2019-05-23 11:18发布

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条回答
地球回转人心会变
2楼-- · 2019-05-23 12:07

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')
     }
   }
 }
查看更多
登录 后发表回答