Is there any way to set default function for prop with function type?
props: {
clickFunction: {
type: 'Function'
default: ????
}
}
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).
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>
This way should work with Vue 2.0
props: {
clickFunction: {
type: 'Function'
default(){
return () => true
}
}
}
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