Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline invert boolean @click in Vue.js

For a simple demo I wanted to invert a boolean I defined inside the data property of my Vue.js instance.

What I tried:

<button @click="!spanVisible" type="button">Toggle</button>

and

<button @click="(!spanVisible)" type="button">Toggle</button>

I want to avoid either writing a separate method or having something like this inside my v-on:click="": spanVisible ? !spanVisible : !spanVisible because it's simply redundant.

So now my questions mostly are: Why doesn't the direct inverting work? What other possibility do I have to keep it short and simple?

edit:

The shortest possible variation i found right now is using spanVisible = !spanVisible, but not sure if that's the most concise version available.

SOLUTION:

The best solution I found was suggested by @Sombriks in the comments: using @click="!spanVisible" only evaluates the inversed value of spanVisible but doesn't alternate it's value, to assign a new value to it you can use @click="spanVisible = !spanVisible", which seems to be the most concise working version for now.

like image 403
Ivan Sieder Avatar asked Dec 16 '16 07:12

Ivan Sieder


2 Answers

I think it is possible to do without any methods

Add a Click Event to reverse the value of the boolean variable. Like this:

@click="showExtra = !showExtra"

In your Script Data:

<script>
  export default {
  return {
    data() {
       showExtra: false
    }
 }
}
</script>
like image 176
Mr. Perfectionist Avatar answered Nov 18 '22 00:11

Mr. Perfectionist


You are doing it wrong. <button v-on:click="toggle" type="button">Toggle</button>

In your script part:

data () {
    return {
        spanVisible: true
    }
},
methods: {
    toggle () {
        this.spanVisible = !this.spanVisible
    }
}

Note that data is declared this way if you are using Vue components. If you are using in file scripting, you will skip return

like image 6
Marek Urbanowicz Avatar answered Nov 18 '22 02:11

Marek Urbanowicz