The Methods in Vue's optionMergeStrategies do not have access to the 'this' keyword

I have been working on developing a Vue plugin. The plugin includes a custom method called customMethod for each component, which I want to execute after the page has been mounted/created. Although everything seems to be working fine in a basic way, I am facing an issue with accessing this inside the customMethod.

When I try to console.log(this), it simply logs 'undefined'.

So, my question is: How can I properly access this inside my customMethod?

var defaultParms = Object.freeze({
start   : function(){},
leave   : function(){}
});



const myPlugin = {
    
    install(Vue, options = []) {
        var ref = Vue.util;
        var extend = ref.extend;

        var assets = Object.create(null);
        extend(assets, defaultParms);
        Vue.options.customMethod = assets;

        
        
        // set option merge strategy
        var strats = Vue.config.optionMergeStrategies;
        if (strats) {
            strats.customMethod = (parent, child, vm)=>{
                
                if (!child) return parent;
                if (!parent) return child;

                var ret = Object.create(null);
                extend(ret, parent);

                for (var key in child) {
                    ret[key] = child[key];
                }
                return ret
            };
        }


        Vue.mixin({
            customMethod:{
                start: function(){
                  console.log('hi') // log 'hi'
                  console.log(this.$appName)  // log 'undefined'
                }
            },
            created: function () {
                if(this.$options.customMethod){
                    this.$options.customMethod.start && this.$options.customMethod.start();
                }
            }
        });


        Vue.prototype.$appName = 'vikash';
    }

}


Vue.use(myPlugin)
new Vue().$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Answer №1

Understanding the concept of the context in JavaScript is essential. It can be manipulated using techniques like bind, call, or apply:

this.$options.customMethod.start.call(this)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to execute operations on two distinct datasets within a single function using RxJS?

Is there a way to perform operations on two separate data collections within a single function in RxJS, returning an observable instead of void? This function is located within a service and I intend to subscribe to it from my component. I believe some re ...

Tips for choosing an <li> element with JavaScript

<style> .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; dis ...

React component that enables radio inputs to repeat upon selection

My current project involves creating a quiz app where users can answer single questions using React on Codepen. I am utilizing an API to fetch a question, along with 3 incorrect answers and 1 correct answer, then storing them in the app's state. Howev ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

Revamping Legacy React Native Projects with the Redux Toolkit

Is there a way to integrate redux toolkit with the existing store, reducer, and dispatch methods in my project without creating new ones? I am looking to update react-redux to the latest version. Please provide guidance and assistance. store.js ` import ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Defining the scope of a variable that is accessed by multiple asynchronous callbacks

Utilizing the async.js library by Caolan McMahon and the jQueryUI progress bar, I am providing real-time feedback to users while multiple asynchronous calls gather data and populate elements in a complex graph. The lingering question is: What is the most ...

What are the drawbacks of relying on a dependent dependency in software development?

In a recent discussion on Stack Overflow, it was suggested that the best practice is to install packages from sub-dependencies for future use in the app, rather than directly from the dependencies node_modules folder. However, my scenario is a bit unique. ...

Show a success message once the jQuery Ajax operation is successful and then refresh the page

I am looking to implement a feature where a Bootstrap alert message is shown immediately following a successful AJAX request and page refresh. success: function(res) { window.location.reload(); $('#success').html('<div class=&qu ...

Preventing an iframe from reloading when transferring it to a new parent using appendChild

I'm looking to relocate an iframe to a different parent element while maintaining the iframe's current state (including scroll position and any entered form data). Unfortunately, when I use appendChild() to move the iframe, it reloads and resets ...

Exploring Nuxt.js: Enhancing User Experience with Dynamic Page

Within my nuxt.config.js file, I included the line loading: '~/components/LoadingBar.vue'. After launching the site, I noticed that my custom page transition only works when the first page visited is anything other than the home page. For insta ...

Implementing position sticky on a div depending on its content text - step by step guide

If the text inside the .newsDate matches the previous or next .newsDate, I want to make its position sticky when scrolling, until it reaches the next .newsMiddleCont div. What I'm trying to achieve: The same date on multiple news items should s ...

Running complex operations within a sorting function just once

I am facing the challenge of sorting an array of objects based on multiple date fields, with the added complexity of excluding certain dates depending on the category. In order to optimize performance, I want to minimize the number of times the getUsefulJo ...

Ways to dynamically assign a class to a single element within a group of identical elements

I have three identical items in the DOM. Specifically, I am referring to a moving line <span class="caret"></span> <ul> <li class="nav-item-1"> <a href="#">ITEM 1</a> <span class="caret"></span> ...

An error of '______ is not defined' was thrown, I'm puzzled as to why

I keep encountering an error that says "weekday is not defined". I'm unsure of the reason behind this issue. Any assistance would be greatly appreciated! (function(exports) { var days = ["monday", "tuesday", "wednesday", "thursday"]; exports. ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine. In reviewing the code s ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...