【问题标题】:Auto reload list items after deletion (Vue.js)删除后自动重新加载列表项(Vue.js)
【发布时间】:2018-11-04 15:10:33
【问题描述】:

问题

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

尝试的解决方案

阅读this question后,我尝试添加projectkey属性。由于 Vue 抱怨 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>

脚本

// under 'methods'
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 => {
          console.log(response);
        }).catch(function (error) {
          console.log(error);
        });
      }).catch(() => {
        return false;
      })
}

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    看起来你只是在删除服务器上的项目,而 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;
          })
    }
    

    【讨论】:

    • 谢谢你!我在一些解决方案中看到了这一点,但不知道它与我的问题有关,您的解释(“Vue 无法知道这一点”)帮助我理解 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多