在vue.js中推送和拼接不更新或删除



我正在尝试使用数组和Vue v-for循环制作一个表单中继器。但我无法推动或切割我的阵列中的任何东西。我得到了一些警告。类型错误:无法读取未定义的的属性"items">

这是我的代码

<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上下文未定义-这就是发生错误的原因**类型错误:无法读取未定义(this(的属性"items"**

你应该这样修改:

repeateAgain() {
this.items.push({

更新

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

例如:(仅用于演示,不要使用此模式(

在以下示例中,this上下文是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()

最新更新