仅在使用Axios的浏览器刷新vuej上删除项目

时间:2018-05-01 19:58:45

标签: vue.js vuejs2 axios

我有一个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>

1 个答案:

答案 0 :(得分:0)

应为this.users

this.users.splice(index, 1).push(response.data);