【问题标题】:Item only removed on browser refresh vuejs with Axios仅在使用 Axios 的浏览器刷新 vuejs 时删除了项目
【发布时间】: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>

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    应该是this.users

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2015-02-18
      • 2015-08-02
      相关资源
      最近更新 更多