For some cases, I don't want to use mixins
in my Plugin.
I am trying to add a custom Methods like created()
, mounted()
, methods{}
, so I can access its property when the component is loaded & run my custom method.
example: "customMethod"
// @root/home.vue
<script>
export default {
name: 'Home',
props: {
msg: String
},
mounted(){
//
},
methods{
//
},
customMethod{
}
}
</script>
.vue file
<script>
export default {
customMethod () { // Custom option.
console.log('custom method executed!')
},
methods: {},
created () {},
mounted () {}
}
</script>
plugins/customMethods.js
const customMethods = {
install (Vue) {
// INSTALL
if (this.installed) return
this.installed = true
Vue.options = Vue.util.mergeOptions(Vue.options, {
created: function () {
if (this.$options.customMethod) { // If found in the component.
this.$options.customMethod() // Execute the customMethod.
}
}
})
}
}
export default customMethods
main.js
import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)
What this does is extend the default options for all Vue instances so the behavior is applied to every single Vue instance created. This is however undocumented at the moment.
Alternatively, this can also be achieved by the use of global mixin in the plugin. (which you don't want for some reason as per your use case.)
Moreover, one advanced use case is we may need special handling when merging custom option values during Vue.extend
. For example, the created
hook has a special merge strategy that merges multiple hook functions into an Array so that all of them will be called. The default strategy is a simple overwrite. If you need a custom merge strategy you will need to register it under Vue.config.optionMergeStrategies
:
Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
// return merged value.
}
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