删除后自动重新加载列表项(Vue.js)

时间:2018-11-04 15:10:33

标签: vue.js

问题

我有一个视图,该视图呈现项目列表并提供删除项目的选项。我的删除方法效果很好-手动刷新页面时,该项消失了。但是,删除项目后,项目列表不会自动重新加载。

尝试的解决方案

阅读this question后,我尝试添加key的{​​{1}}属性。由于Vue抱怨project最好是字符串或整数,因此我将key更改为key。但是,这些都不能解决我的问题。

模板

project.id

脚本

<el-col :span="8" v-for="project in projects" :key="project.id">
      <el-card class="project-card">
        <!-- Click to navigate to project -->
        <div @click='navigateProject(project)' class="project-card-inner">
          <!-- Dummy data -->
          <br><em>{{ 'Project ' + project.id }}</em>
        </div>
        <!-- Delete project -->
        <div @click='deleteProject(project)' class="el-icon-delete"></div>
      </el-card>
</el-col>

1 个答案:

答案 0 :(得分:0)

好像您只是删除服务器上的项目,Vue无法知道这一点。我建议您在发送axios请求之后,还以本地状态删除该项目。像这样:

deleteProject(project) {
  this.$confirm('Are you sure you want to delete this project? '
    + 'This cannot be undone.', 'Warning', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        const request_url = this.url + project.id + '/';
        this.$message({
          type: 'success',
          message: 'Project deleted.'
        });
        return axios({
          method: 'delete',
          url: request_url,
          id: project.id
        }).then(response => {
          // Logic to delete local state
          const projectIndex = this.projects.findIndex(p => p.id === project.id)
          this.projects.splice(projectIndex, 1)
        }).catch(function (error) {
          console.log(error);
        });
      }).catch(() => {
        return false;
      })
}