Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement inside Vue click to change function to be run?

How can I use an if statement inside either a v-bind, v-on or @ click to handle which function gets run?

What I have right now that only sort of works is this (the if statement is in shorthand javascript):

        <li v-for="entry in entries.entries"><button type="button" @click="entry.entries?openSub($event):'entry.action'">{{entry.title}}</button>

So basically, if the buttons list item has sub entries inside it the button should trigger the function that adds the submenu-active class to the list item, and if the list item the button is in does not have any sub entries it should run whatever function has been assigned to the button.

I say it sort of works because it does run the openSub($event) part correctly, but it neither runs nor even adds the function that's supposed to be run if there are no entries.

like image 790
Simon Hyll Avatar asked Apr 29 '17 16:04

Simon Hyll


1 Answers

The problem is you're not executing a function.

new Vue({
  el: '#app',
  data: {
  	bool: true
  },
  methods: {
  	one() {
    	console.log('one');
      this.bool = !this.bool;
    },
    two() {
    	console.log('two');
      this.bool = !this.bool;
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <button @click="bool ? one() : two()">Click</button>
</div>

So, there should be entries.action() in your code.

<li v-for="entry in entries.entries"><button type="button" @click="entry.entries ? openSub($event) : entry.action()">{{entry.title}}</button>

like image 134
Egor Stambakio Avatar answered Oct 22 '22 15:10

Egor Stambakio