[英]How to check if string exists before doing a POST/PUT request?
I am using VueJS and I got a web form where a user can check an html checkbox labeled "Active" to designate whether an item (named branch
) is active
.我正在使用 VueJS,我得到了 web 表单,用户可以在其中检查标记为“活动”的 html 复选框以指定项目(名为branch
)是否active
。 If the input box is left unchecked, that means the item is inactive
.如果输入框未选中,则表示该项目inactive
。 IF a branch
is inactive
, I dynamically append the text (inactive)
to the branch
property.如果一个branch
是非inactive
的,我动态 append 文本(inactive)
到branch
属性。 The data collection from the form is then sent to a database/remote api.然后将表单中的数据收集发送到数据库/远程 api。 Pretty straightforward.很简单。 UI examples below:下面的用户界面示例:
My question is: How can I REMOVE the string (inactive)
from the branch name if it already exists?我的问题是:如果它已经存在,我如何从分支名称中删除字符串(inactive)
?
Here's my data()
object and relevant method()
:这是我的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' })
})
Thanks for any tips on how I can do this efficiently!感谢您提供有关如何有效地做到这一点的任何提示!
You can use String.prototype.replace()
to replace the string if it exists.您可以使用String.prototype.replace()
替换字符串(如果存在)。
branchEdit.branch = this.branch.active ?
this.branch.branch.replace(' (inactive)', '') :
this.branch.branch + ' (inactive)';
If branch name contains the string (inactive)
, it is removed.如果分支名称包含字符串(inactive)
,则将其删除。 If not, nothing is changed.如果没有,什么都不会改变。
don't have to make changes to the original the.branch
object.不必对原来的the.branch
object做改动。 create a temp clone of it, post to the API, then done.创建它的临时克隆,发布到 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)
.....
}
if you want to display branch + " (inactive)"
in web page, since you are using vue.js.如果您想在 web 页面中显示branch + " (inactive)"
,因为您使用的是 vue.js。 use v-if
would work:使用v-if
会起作用:
<span v-if="!branch.active">(inactive)</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.