[英]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.