代码之家  ›  专栏  ›  技术社区  ›  sofarsophie

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

  •  0
  • sofarsophie  · 技术社区  · 6 年前

    问题

    读后 this question ,我尝试添加 key 的属性 project . 因为Vue抱怨 钥匙 成为 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;
          })
    }
    
    1 回复  |  直到 6 年前
        1
  •  5
  •   Andreas    6 年前

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