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.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With