Hamed Kamrava
Hamed Kamrava

Reputation: 12847

How to use JavaScript functions in Vue directives?

Assume I have a JS function like this:

function myFunc()
{
   return true;
}

Now, I want to show an element if the output of is true:

<p v-if="myFun()">I am Test</p>

I know I can write this myFunc method inside Vue methods but I don't want this.

Any idea would be great appreciated.

Upvotes: 1

Views: 143

Answers (2)

Emīls Gulbis
Emīls Gulbis

Reputation: 2070

You can point to your function in many ways. One of these:

var myFunc = function(){
	return true;
}

new Vue({
  el: '#app',
  methods : {
    yourFunc() {
      return myFunc();
    }
  }
});
<div id="app">
  <p v-if="yourFunc">test</p>
</div>

https://jsfiddle.net/1nnav731/

Upvotes: 1

reinerBa
reinerBa

Reputation: 1660

You can link your vanilla function in the methods section methods:{ myFun: myFun}

or write your own directive:

Vue.directive('visible', function (el, binding) {
    el.style.visibility = binding.value ? 'visible' : 'hidden';
});

Upvotes: 0

Related Questions