Home > Net >  @click ternary operations in Vue.js
@click ternary operations in Vue.js

Time:06-30

I'm trying to do the following but it keeps returning [plugin:vite:vue] Unexpected token (1:27) error in Vue.js:

@click="selectedFiles.push(file.id); selectedFiles.length < 1 ? isCollapse=false: isCollapse=true"

Basically when this image is clicked:

  1. It should first push the file to selectedFiles array
  2. .. and then check if the length is < 1 and change the isCollapse boolean accordingly.

The code works fine without the ternary operation so I believe it's a syntax issue.

CodePudding user response:

Did you try like:

@click="[selectedFiles.push(file.id), isCollapse = !!selectedFiles.length]"

CodePudding user response:

You can actually avoid the ternary entirely.

isCollapse = selectedFiles.length >= 1

As far as ternary syntax goes spaces on either side of the colon are important.

selectedFiles.length < 1 ? isCollapse = false : isCollapse = true

Also, I would definitely recommend using a method for this. Any time you need to perform more than 1 very simple js expression in response to an event, a method will be much more readable and maintainable.

  • Related