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
. If the input box is left unchecked, that means the item is inactive
. IF a branch
is inactive
, I dynamically append the text (inactive)
to the branch
property. The data collection from the form is then sent to a database/remote api. Pretty straightforward. UI examples below:
My question is: How can I REMOVE the string (inactive)
from the branch name if it already exists?
Here's my data()
object and relevant 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.
branchEdit.branch = this.branch.active ?
this.branch.branch.replace(' (inactive)', '') :
this.branch.branch + ' (inactive)';
If branch name contains the string (inactive)
, it is removed. If not, nothing is changed.
don't have to make changes to the original the.branch
object. create a temp clone of it, post to the API, then done.
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. use v-if
would work:
<span v-if="!branch.active">(inactive)</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.