【发布时间】:2018-05-01 19:58:45
【问题描述】:
我有一个 vuejs 2.5.2 应用程序,我试图从 API 中删除一个项目。我实际上是在删除记录,但这只有在我刷新浏览器时才明显。我在控制台中有以下消息:
Users.vue?7efa:60 Uncaught (in promise) TypeError: Cannot read property 'splice' of undefined
我可以很好地从 API 中提取数据,而且我也可以写入新记录,它会在浏览器中更新而无需刷新。
整个组件的代码是:
<div id="users">
<div v-for="(user, index) in users" :key="user.id">
<p>{{user.name}} is my {{user.relation}}<span class="glyphicon glyphicon-trash" aria-hidden="true" v-on:click="removeUser(user.id, index)"></span></p>
<hr />
</div>
<form id="users" v-on:submit.prevent="onSubmit" method="POST">
<input type="text" v-model="name" placeholder="name"/>
<input type="text" v-model="relation" placeholder="relation"/>
<input type="submit" class="btn btn-primary" name="" value="Create User"/>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
users: [],
errors: []
}
},
// Fetches users when the component is created.
created() {
axios.get('https://sandboxback.herokuapp.com/users')
.then(response => {
// JSON responses are automatically parsed.
this.users = response.data
})
.catch(e => {
this.errors.push(e)
})
},
methods: {
onSubmit: function (event) {
axios.post('https://sandboxback.herokuapp.com/users', {
name: this.name,
relation: this.relation
})
.then(response => {
this.users.push(response.data)
})
.catch(function (error) {
console.log(error);
});
},//end on submit
removeUser: function (id, index) {
axios.delete('https://sandboxback.herokuapp.com/users/'+id)
.then(response => {
this.user.splice(index, 1).push(response.data)
});
},
} //end method
}
</script>
【问题讨论】: