Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: default value for prop function

Is there any way to set default function for prop with function type?

props: {
    clickFunction: {
        type: 'Function'
        default: ????
    }
}
like image 686
bakis Avatar asked Dec 06 '18 21:12

bakis


3 Answers

I'd say, always provide a default value that matched the type you specified: makes things much more easier to reason about. Here, what you are looking for would be a noop function (a.k.a. a function that does nothing):

props: {
  clickFunction: {
    type: Function
    default: () => {}
  }
}

You can then use this.clickFunction() in your code without checking it defensively first: it is always a function. Be sure you don't get mixed up with the default value for an Object prop, that would be an empty object:

props: {
  someObject: {
    type: Object
    default: () => ({})
  }
}

In Vue, Object and Array props must have their default value returned by a function to ensure they are distinct for every instance of the component (which does not seem to be required for Function props, but docs indeed aren't crystal clear about this).

like image 41
neemzy Avatar answered Nov 12 '22 13:11

neemzy


Yes:

Vue.component('foo', {
  template: '<div>{{ num }}</div>',
  props: {
    func: {
      type: Function,
      default: () => 1,
    },
  },
  data() {
    return { 
      num: this.func()
    }
  }
})

new Vue({
  el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <foo></foo>
</div>
like image 141
thanksd Avatar answered Nov 12 '22 15:11

thanksd


This way should work with Vue 2.0

props: {
    clickFunction: {
        type: 'Function'
        default(){
          return () => true
        }
    }
}
like image 4
Tamer A. El Sayed Avatar answered Nov 12 '22 14:11

Tamer A. El Sayed