Home  >  Q&A  >  body text

In Nuxt.js how to push object to array in data attribute

I want to push an object into an array inside a data attribute in my nuxt project. But I am getting error like

Cannot read property of undefined (read 'push')

This is my js part

<script>
export default {
  data() {
    return {
      form: {
        gallery: [{
          id: null,
          imgurl: null
        }]
      }
    }
  },

  methods: {
    async uploadGallery() {
      var myimg = "imageurl getting after upload";
      var imgData = {};
      imgData['imgurl'] = myimg;
      imgData['id'] = "someid";
      this.form.gallery.push(imgData);
    },
  }
}
</script>

P粉060112396P粉060112396235 days ago340

reply all(1)I'll reply

  • P粉593118425

    P粉5931184252024-02-27 11:05:43

    I tried your code like above. When I click the button it is working. You may not be able to access form.gallery because the uploadGallery triggered is in the wrong lifecycle hook.

    reply
    0
  • Cancelreply