使用v-for时如何更新文本输入值

时间:2019-06-17 23:11:26

标签: vue.js vue-component

我在这里已经看了很多问题,但是从我能想到的角度来看,这些问题都不适合我的情况。

这是设置:

  1. 在我的页面上,我有一个名为ownerQuestions的计算对象
  2. 我使用v-for遍历此对象并使用其值填充组件
  3. 此组件在页面上生成输入
  4. 最初这些输入被禁用
  5. 用户单击Edit按钮,输入更改为可编辑,以允许用户编辑值。
  6. 当用户单击Edit按钮时,我使用v-if将其更改为Cancel按钮
  7. 如果用户单击Edit,对任何输入进行更改,然后单击Cancel,则输入的值应回到用户进行任何更改之前的原始值。

这是页面上的代码。我试图去除一些东西以使其更简单,希望我没有拿出任何对说明目的很重要的东西:

<template>
  <section class="d-flex flex-column container">
    <div class="text-center align-self-center app-page" v-if="loadingQuestions || !ownerQuestions.length">
      <h3>Getting Questions</h3>
      <div class="spinner mx-auto mb-3"></div>
    </div>
    <section class="align-self-center app-page" v-else>

      <!-- owner info display -->
      <div class="question-group-header">
        <h4 class="text-truncate">Owner Information</h4>
        <a href="javascript:;" v-if="displayOnly" @click="editTextInputs()" class="edit-button ml-2"><no-ssr><i class="far fa-pencil"></i></no-ssr><span id="ownerInfoEditBtn" class="d-sm-inline d-none editBtn1">Edit</span></a>
        <a href="javascript:;" v-else @click="cancelEditTextInputs()" class="edit-button ml-2"><no-ssr><i class="far fa-pencil"></i></no-ssr><span id="ownerInfoEditBtn" class="d-sm-inline d-none editBtn1">Cancel</span></a>        
      </div>

      <div class="d-flex flex-wrap justify-content-between mb-5">
        <div id="questions" v-for="(question, index) in ownerQuestions" :key="question.id" class="col-12 col-md-6 px-0 py-2
              d-flex flex-wrap align-content-start
              border-bottom border-gray-200 question-wrap">
          <borrower-attribute              
              :question="question"
              v-model="question.value"
              :update-index="index"
              :invalidity="invalidity"
              formLayout="inline"
              @answer="updateQuestion" 
              v-bind:id="question.id"
              :displayOnly="displayOnly"></borrower-attribute>
        </div>
      </div>
    </section>
  </section>
</template>

<script>
import BorrowerAttribute from '~/components/borrowerAttributes/BorrowerAttribute.vue'
import Modal from '~/components/modal.vue'
import { mapGetters, mapState } from 'vuex'
import QuestionsStore from '~/store/questions.store'
import documentsModule from '~/store/documents'
import { displayValue } from '~/libs/borrower-attribute'
import { authDownload } from '~/libs/upload-service'
import EditQuestionsModal from '~/components/EditQuestionsModal.vue'
import SmoothScroll from '~/libs/smooth-scroll'
import { lsUtils } from '~/libs/ls-utils-service'
import orderBy from 'lodash/orderBy'

export default {
  name: 'Submit',
  layout: 'renewal-app',
  components: {
    'borrower-attribute': BorrowerAttribute,
    'modal': Modal,
    'edit-questions-modal': EditQuestionsModal
  },
  data () {
    return {
      submitting: false,
      invalidity: {},
      displayOnly: true,
      baseOwnerQuestions: {},
      backupOwnerQuestions: {}
    }    
  },
  async beforeCreate () {
    await this.$store.dispatch('borrower/getBorrower', {'forceReload': true})
    await this.$store.dispatch('borrower/getBorrowerValues')
  },
  mounted () {
    SmoothScroll.goTo(0)
    const currentProgress = this.$store.state.progress.appProgress['submit']
    if (!currentProgress || currentProgress < 1) {
      this.$store.dispatch('progress/saveProgressTab', { key: 'submit', value: '1' })
    }        
  },
  async created () {
    await this.$store.dispatch('borrower/getBorrower')
    if (!this.ownerQuestions.length) {
      await this.$store.dispatch('questions/initializeSubmitPage')
    }
  },
  computed: {
    ...mapState({
      authUser: state => state.authUser,
      borrower: state => state.borrower,
      loadingQuestions: state => state.questions.loadingQuestions
    }),
    ...mapGetters('questions', [
      'reviewQuestions',
      'displayableQuestions'
    ]),
    ...mapGetters('document', ['requirements']),
    ownerQuestions () {
      return orderBy(
        this.reviewQuestions.filter((q) => q.appSection === 'personalInfo'),
        ['group', 'groupOrder'], ['desc', 'asc']
      )
    }
  },
  methods: {    
    updateQuestion ({ attr, isInvalid }) {
      if (!attr || attr.alias === undefined) {
        return false
      }
      if (isInvalid) {
        return false
      }
      this.$store.commit('questions/mergeAnswers', { [attr.alias]: attr })
    },
    async submitApp () {
      await this.$store.dispatch('borrower/getBorrower')
      await this.$store.dispatch('borrower/setApplicationComplete')
      this.$router.push('/dashboard')
    },
    download (path, params, newTab, filename) {
      return authDownload(path, params, newTab, filename)
    },
    editTextInputs () {
      var editFields = document.getElementsByClassName("form-control");
      this.backupOwnerQuestions = JSON.parse(JSON.stringify(this.ownerQuestions));
      for (var i = 0; i < editFields.length; i++) {        
          this.displayOnly=false
          editFields[i].style.border = "1px solid black";
      }      
    },
    cancelEditTextInputs () {
      this.ownerQuestions = JSON.parse(JSON.stringify(this.backupOwnerQuestions));
      var cancelEditFields = document.getElementsByClassName("form-control");
      this.displayOnly=true
      for (var i = 0; i < cancelEditFields.length; i++) {
        cancelEditFields[i].style.border = "";
      }
    }
  }
}
</script>

尝试创建一个名为backupOwnerQuestions的对象,然后在editTextInputs javascript函数中将此对象设置为等于ownerQuestions对象的原始值。最后,在我的cancelEditTextInputs函数中,我尝试将ownerQuestions设置回存储在backupOwnerQuestions对象中的值。

但是,这不起作用,因此我问了这个问题。我什至不知道这是否是正确的方法。请让我知道是否需要我提供其他信息。

1 个答案:

答案 0 :(得分:0)

问题是这一行:

this.ownerQuestions = JSON.parse(JSON.stringify(this.backupOwnerQuestions));

ownerQuestions是由函数定义的计算属性:

ownerQuestions () {
  return orderBy(
    this.reviewQuestions.filter((q) => q.appSection === 'personalInfo'),
    ['group', 'groupOrder'], ['desc', 'asc']
  )
}

所以您不能只是覆盖它。更糟糕的是,您正在通过reviewQuestionsownerQuestions对象上的字段传递给v-model指令。由于reviewQuestions来自vuex商店,因此只能使用突变对其进行编辑。

您可以尝试创建要编辑的副本,然后在取消编辑时还原为原始副本,而不是编辑原始副本并对其具有指针的任何内容进行更改。

类似的东西:

this.editableQuestions = JSON.parse(JSON.stringify(this.ownerQuestions));

然后在v-for上方editableQuestions,当用户取消编辑时,只需调用

this.editableQuestions = JSON.parse(JSON.stringify(this.ownerQuestions));
再次

。这种方法可能需要您做更多的工作才能将其完全吸收到您的代码中。我主要是想找出问题所在,并为您指明正确的方向。