vue.js 推送拼接未更新或删除

Push and splice not updating or deleting in vue.js

我正在尝试使用数组和 Vue v-for 循环制作表单转发器。但我无法在数组中推送或切片任何内容。我得到了一些警告。 TypeError: 无法读取未定义的 属性 'items'

Here is my code

<template>
  <b-form @submit.prevent="repeateAgain">
     <b-row
      v-for="(item, index) in items"
      :id="item.id"
      :key="item.id"
     >
       <b-col>
         <b-form-group>
           <b-form-input
            placeholder="Email"
           />
        </b-form-group>
      </b-col>
      <b-col>
        <b-form-group>
          <b-form-input placeholder="Email" />
        </b-form-group>
      </b-col>
      <b-col>
        <b-form-group>
           <b-form-input placeholder="Email" />
        </b-form-group>
      </b-col>
      <b-col>
        <b-form-group>
          <b-button
           variant="outline-danger"
            @click="removeItem(index)"
           >
            <i class="feather icon-x" />
             <span class="ml-25">Delete</span>
           </b-button>
         </b-form-group>
       </b-col>
     </b-row>
        <hr>
     <b-form-group>
       <b-button
         variant="primary"
         @click="repeateAgain"
        >
         <i class="feather icon-plus" />
         <span class="ml-25">Add</span>
       </b-button>
     </b-form-group>
  </b-form>
</template>

<script>
import {
  BForm, BFormGroup, BFormInput, BRow, BCol, BButton,
} from 'bootstrap-vue'

export default {
  components: {
    BForm,
    BRow,
    BCol,
    BButton,
    BFormGroup,
    BFormInput,
  },
  data: () => ({
    items: [{
      id: 1,
      title: 'Do the dishes',
    },
    {
      id: 2,
      title: 'What to do ?',
    }],
    newTodoText: '',
    nextTodoId: 2,
  }),
  methods: {
    repeateAgain: () => {
      this.items.push({
        id: this.nextTodoId += +this.nextTodoId,
        title: this.newTodoText,
      })
      this.newTodoText = ''
    },
    removeItem: index => {
      this.items.splice(1)
      console.log(index)
    },
  },
}
</script>

我也尝试使用 slice 方法删除特定行,但它不起作用。 我忘了什么??

你不应该在 Vue 中为 datamethods 使用箭头函数,因为箭头函数有它们自己的上下文 (this)

repeateAgain: () => {
      this.items.push({

在调用 repeateAgain 方法时,this 上下文未定义 - 这就是错误发生的原因 ** TypeError: Cannot read 属性 'items' of undefined (这个)**

你应该这样修改它:

repeateAgain() {
      this.items.push({


更新

@submit.prevent="repeateAgain" - 这就是我所说的“场合”。另一方面,由于该方法未绑定到 methods: { 对象,而是绑定到相对上下文(此处为 none - 未定义),如果它在 class 中,则 class 实例将是上下文。

例如:(仅供演示,请勿使用此模式)

在下面的例子中,thiscontext 是 MyWrappedCmp 的一个实例


import {
  BForm, BFormGroup, BFormInput, BRow, BCol, BButton,
} from 'bootstrap-vue'

class MyWrappedCmp {
  getComponent(){
    return {
      methods: {
        repeateAgain: () => {
          // “this” context is an instance of MyWrappedCmp
          // ...
         }
      }
    }
}

const myWrapped = new MyWrappedCmp()

export default myWrapped.getComponent()