.vue file
<script>
export default {
customMethod () { // This is a 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) { // Check if the custom method exists in the component.
this.$options.customMethod() // Execute the customMethod.
}
}
})
}
}
export default customMethods
main.js
import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)
This code extends the default options for all Vue instances so that the behavior applies to every single Vue instance created. Although currently undocumented, it provides extra flexibility.
Alternatively, you can achieve similar effects using global mixins in the plugin, but for specific reasons outlined in your use case, this approach may be avoided.
Furthermore, a more advanced use case involves implementing special handling during the merging of custom option values when utilizing Vue.extend
. For instance, the created
hook incorporates a specific merge strategy that combines multiple hook functions into an Array to ensure they are all called. The default strategy involves simple overwriting, while custom merge strategies can be defined under Vue.config.optionMergeStrategies
:
Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
// Define and return the merged value here.
}