【问题标题】:How to push an object to array in data properties in nuxtjs如何将对象推送到nuxtjs中数据属性中的数组
【发布时间】:2022-01-08 20:11:45
【问题描述】:

我想在我的 nuxt 项目中将对象推送到数据属性中的数组中。但我收到了类似的错误

无法读取未定义的属性(读取“推送”)

这是我的 js 部分

<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>

【问题讨论】:

  • 这意味着this.form.gallery 在某些时候是undefined。您的代码中的其他地方可能存在一些异步问题。
  • 另外,随意写成这样imgData.imgurl,更简单。
  • 你什么时候调用这个方法?
  • 原谅我!这都是我后端的错字问题,在异步数据中,我使用来自 api 的返回值替换本地表单数据。在后端,我将画廊错误地输入为厨房,这就是为什么我面临这样的问题。
  • 'this' 内容在 "fetch" 钩子中可用。您可能在 created 钩子中调用该方法。更多关于nuxt生命周期的信息:nuxtjs.org/docs/concepts/nuxt-lifecycle

标签: vue.js nuxt.js


【解决方案1】:

我试过你上面的代码。当我单击按钮时,它正在工作。可能您无法访问 form.gallery,因为触发的 uploadGallery 处于错误的生命周期挂钩中。

<template>
  <div>
    {{form.gallery}}
     <button @click="uploadGallery">click</button>
  </div> 
</template> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2020-05-21
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多