从Vue中的数组中删除嵌套对象

时间:2018-10-02 17:52:39

标签: ajax vue.js axios vuex

试图从数组中删除嵌套对象。我进行了一些研究,并遇到了一个与我的Vue.js Remove a Nested Object from Array类似的示例。

但是,由于我尝试使用ajax请求删除对象,因此我的问题稍微复杂一些。本质上,我的参与度数组包含问题的嵌套对象

enter image description here

这就是我如何显示参与问题的列表

<div v-for="question in engagement.questions" :key="question.id">
        <div>
          <div ">
            {{ question.question }}
          </div>
          <div >
            <span>Answered: </span>
            <input type="checkbox" v-model="question.answered">
          </div>
        </div>
      </div>

这是删除问题的按钮

<b-btn  @click="deleteQuestion(engagement, question)">Confirm</b-btn>

这是调度到商店的方法

deleteQuestion(engagement, question) {
      this.$store.dispatch('deleteQuestion', id)
      .then(() => {
        this.$router.push({path: '/engagement/' +this.engagement.id , query: {alert: 'The Question Was Succesfully Deleted'}});
      })
    },

这是存储方法

deleteQuestion(context, id) {
      axios.delete('/questions/' + id)
      .then(response => {
          context.commit('deleteQuestion', id)
      })
      .catch(error => {
          console.log(error)
      })                
    },

现在我的警报是“未定义ID”,尽管我在此代码的其他变体中会出现500个内部服务器错误,这使我认为我没有正确捕获问题的ID,因此它知道删除哪一个...

以下是我在控制台中收到的警报。我也做到了,这就是观察者第一个箭头指向的方向

console.log(question)

enter image description here

1 个答案:

答案 0 :(得分:0)

问题在于,包含@ click =“ deleteQuestion”的b-model元素位于包含v-for的div之外,因此当我单击b-modal按钮时,它没有获取ID这个问题。因此,我将b-modal移到了该div上并且它起作用了。谢谢您的帮助。

<div class="card mb-3"  v-for="(question, index) in engagement.questions" :key="index">
        <div class="card-header">
          <div class="h6 m-0 justify-content-between d-flex">
            <router-link class="btn btn-sm btn-primary mr-3" to="#" ><i class="far fa-edit mr-2"></i>Edit</router-link> 
            <b-btn class="outline-secondary" size="sm" v-b-modal.myQuestion><i class="fas fa-trash"></i><span class="ml-2">Delete</span></b-btn>
          </div>
        </div>
        <div class="card-body bg-light d-flex justify-content-between">
          <div class="h4 mr-5 text-left">
            {{ question.question }}
          </div>
          <div class="ml-5 d-flex align-self-center">
            <span class="font-weight-bold mr-2">Answered: </span>
            <input class="mt-2" type="checkbox" v-model="question.answered">
          </div>
        </div>

        <!-- this is the modal for deleting a question -->
      <b-modal id="myQuestion" ref="myModalQuestion" hide-footer title="Delete Question">
        <div class="d-block text-left">
          <h5>Are you sure you want to delete question?</h5>
          <br>
          <p><strong>*Warning:</strong> Can not be undone once deleted.</p>
        </div>
        <div class="d-flex">
          <b-btn class="mt-3" variant="danger" @click="hideModal">Cancel</b-btn>
          <b-btn class="mt-3 ml-auto" variant="outline-success" @click="deleteQuestion(engagement, question.id)">Confirm</b-btn>
        </div>
      </b-modal>

      </div>