Welcome to VueJs mastering the API, today we will talk about the optionMergeStrategies method.
It provides us a powerful way to create plugins to intercept and modify the default behavior of Vue hook life cycle.
None of the official documentationhelps me to learn how to use it, So after some research finally learn a path.
How to use optionMergeStrategies
-
Create the file:
src/plugins/customMethods.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst 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; -
Now to install the plugin add the code to your
src/main.js
:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport Vue from "vue"; import App from "./App.vue"; import customMethods from "@/plugins/customMethods.js"; Vue.use(customMethods); // ... ommited -
Once installed our customMethod will be available in any component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters<template> <div>Test page</div> </template> <script> export default { name: "Mycomponent", beforeCreate() { console.log("beforeCreate"); }, created() { console.log("created"); }, beforeMount() { console.log("beforeMount"); }, mounted() { console.log("mounted"); }, customMethod() { console.log("custom method executed!"); }, }; </script>
The customMethod executes him code right before the default createdMethod code, so if you need to run something before the default hooks code just replace the line 8 to another hookMethod from customMethod.js
or overwrite another hookMethod.
If I help you please consider helping me too. Leave comments, share it. Believe me, your feedback it's really important to me.
Top comments (0)