DEV Community

Cover image for Modifying hook methods with optionMergeStrategies
Jhonatan Morais
Jhonatan Morais

Posted on

1 1

Modifying hook methods with optionMergeStrategies

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

  1. Create the file: src/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;
  2. Now to install the plugin add the code to your src/main.js:

    import Vue from "vue";
    import App from "./App.vue";
    import customMethods from "@/plugins/customMethods.js";
    Vue.use(customMethods);
    // ... ommited
    view raw main.js hosted with ❤ by GitHub
  3. Once installed our customMethod will be available in any component

    <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>
    view raw MyComponent.vue hosted with ❤ by GitHub
  4. The console with print the messages at following order:
    Life cycle console prints

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.

References

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay