簡體   English   中英

如何在執行 POST/PUT 請求之前檢查字符串是否存在?

[英]How to check if string exists before doing a POST/PUT request?

我正在使用 VueJS,我得到了 web 表單,用戶可以在其中檢查標記為“活動”的 html 復選框以指定項目(名為branch )是否active 如果輸入框未選中,則表示該項目inactive 如果一個branch是非inactive的,我動態 append 文本(inactive)branch屬性。 然后將表單中的數據收集發送到數據庫/遠程 api。 很簡單。 下面的用戶界面示例:

在此處輸入圖像描述 在此處輸入圖像描述

我的問題是:如果它已經存在,我如何從分支名稱中刪除字符串(inactive)

這是我的data() object 和相關method()

  data() {
    return {
      branch: {
        division_id: null,
        branch: '',
        active: false,
        branch_id: null
      },

onSubmitUpdate() {
      this.loading = true
      let branchEdit = this.branch
      branchEdit.branch = this.branch.active ? this.branch.branch : this.branch.branch + ' (inactive)'
      ApiService.updateBranch(branchEdit)
        .then(() => {
          this.loading = false
          //this.$router.push({ path: '/home' })
        })

感謝您提供有關如何有效地做到這一點的任何提示!

您可以使用String.prototype.replace()替換字符串(如果存在)。

branchEdit.branch = this.branch.active ? 
    this.branch.branch.replace(' (inactive)', '') : 
    this.branch.branch + ' (inactive)';

如果分支名稱包含字符串(inactive) ,則將其刪除。 如果沒有,什么都不會改變。

不必對原來的the.branch object做改動。 創建它的臨時克隆,發布到 API,然后完成。

onSubmitUpdate() {
      this.loading = true
      // clone it
      let clone = Object.assign({}, this.branch)
      clone.branch = clone.active ? clone.branch : clone.branch + ' (inactive)'
      ApiService.updateBranch(clone)
      .....
}

如果您想在 web 頁面中顯示branch + " (inactive)" ,因為您使用的是 vue.js。 使用v-if會起作用:

<span v-if="!branch.active">(inactive)</span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM