简体   繁体   中英

Vue JS ternary expression

i'm using Vue JS and am trying to use a ternary expression to conditionally change the value of something, I'm struggling with how to convert the following to a ternary expression, here's my method, by default: isLoading is true

fetchData(showLoading) {
  if (showLoading) {
    this.isLoading = true
  } else {
    this.isLoading = false
  }
}

Don't use the conditional operator here, just assign showLoading to isLoading , assuming you're passing a boolean:

this.isLoading = showLoading;

If you're not necessarily passing a boolean, then cast to boolean first (if needed):

this.isLoading = Boolean(showLoading);

If you had to use the conditional operator, it would be:

this.isLoading = showLoading ? true : false;
fetchData(showLoading) {
 showLoading ? (this.isLoading = true) : (this.isLoading = false)
}

your 'showLoading' data is I guess Boolean and you dont need if else.

this.isLoading = showLoading

and it's wrong below code will get error

this.isLoading = showLoading ? true : false; 

看起来你想强制 showLoading 是一个布尔值所以试试这个

this.isLoading = !!showLoading;
this.showLoading = isLoading ? true : false;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM