What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way:

function (Vue, options) {
    Vue.$detector = new TranslatableStringDetector();
}

Utilizing it within a computed property in my component is done like so:

export default {
    // ...
    computed: {
        decoratedProfileName () {
            return this.$detector.decorate(this.$props.profileName);
        }
    }
    // ...
}

Setting it up in the Karma/Mocha test looks like this:

before(() => {
            const localVue = createLocalVue();
            localVue.use(Vuex);
            localVue.use(TranslationDetector);

            store = new Vuex.Store(cloneDeep(storeDefinition));
            store.commit(SET_USER_DATA, userData);

            wrapper = shallowMount(Avatar, {
                localVue,
                store,
                propsData: {
                    id: 0,
                    inputElPrio: 2,
                    profileName: 'Default'
                }
            });
        });

The error occurs during shallowMount() with the following message:

[Vue warn]: Error in config.errorHandler: "TypeError: Cannot read property 'decorate' of undefined"
TypeError: Cannot read property 'decorate' of undefined
    at VueComponent.decoratedProfileName (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:132143:35)
    at Watcher.get (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:71415:25)
   [... more errors ...]
[Vue warn]: Error in render: "TypeError: Cannot read property 'decorate' of undefined"

found in

---> <Avatar> at src/components/controls/Avatar.vue
       <Root>
TypeError: Cannot read property 'decorate' of undefined
    at VueComponent.decoratedProfileName (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:132143:35)
   [... more errors ...]

This inconsistency has left me puzzled. Despite verifying that localVue.$detector is properly configured using console.debug(), I still face issues accessing it as this.$detector within my component. This leads to an unexpected "undefined" result in scenarios such as:

export default {
    // ...
    created: function () {
        console.debug(this.$detector);
    }
    // ...
}

Answer №1

After misunderstanding the information on the Vue.js website, I wrongly interpreted "global" to mean a single object accessible by all components. Following the guidance from the documentation, my intention was to create an "instance method" that would render a property for all components. This subtle distinction proved crucial in solving the issue at hand. Surprisingly, I had overlooked this approach earlier as I was focused on troubleshooting another problem. The correct installation code should be implemented as follows:

function (Vue, options) {
    Vue.prototype.$detector = new TranslatableStringDetector();
}

Answer №2

My understanding is that utilizing lambda functions (also known as anonymous functions) in the lifecycles hooks will not be effective because this references the parent object, which is null.

It is recommended to use function() { /*your code*/ } instead.

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

Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet? var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api"); httpWebRequestAuthentication.ContentType = "application/json"; httpWebRequestAuthentication.Accept ...

JS function to reverse a string

Not to worry, I've managed to figure out how to reverse a string (a one-word string at least). > function reverse(s){ > return s.split("").reverse().join(""); } Is there a way to reverse a string in this manner: "Dady come home" -> "yd ...

How can I determine the package version that is being used when requiring it in Node.js?

I am currently working on resolving an issue with a node module that does not have a package.json. The module contains references to cheerio and superagent: var log = console.log.bind(console), superagent = require('superagent'), cheerio ...

The p5js function pixelDensity() does not provide improved resolution on retina screens

Currently, I am working on a project that involves generating collages from sets of photos. This process includes averaging the pixels' colors of the images and then using that averaged color to plot points on the canvas. However, when I zoom in on re ...

Unable to retrieve data. Issue: Unable to send headers after they have already been sent to the client

Experiencing an error while attempting to retrieve posts from a specific user. The code for fetching the data appears to be correct, so it's unclear where the error is originating from. Error from server side https://i.stack.imgur.com/ep1Xh.png Error ...

Ensure that the fields in Laravel 5.7 are properly validated by using asterisks and the required_if

My Vue form allows users to add work experience to their profile, with the option to add additional experiences by clicking a button. The structure of the form is illustrated below: <div class="item"> <div class="row"> <div clas ...

Utilizing the @keypress event handler in VueJS

I am attempting to incorporate the onkeypress event within a Vue component. My goal is to allow only numbers on keypress while disallowing all other key codes. Here is what I have tried: Implementing the onkeypress event works perfectly! <input type=&q ...

No matter what I do, I can't seem to stop refreshing the page. I've attempted to prevent default, stop propagation, and even tried using

Below is the code I have written for a login page: import { useState } from "react"; import IsEmail from "isemail"; import { useRouter } from "next/router"; import m from "../library/magic-client"; import { useEffect ...

Efficiently pinpointing the <div> element with precision using jQuery

I am building an interactive quiz for users of my app. The questions are table based, and can be answered "yes," "no," or "maybe." If the user answers "no" or "maybe," I would to slide open an informational panel that lives beneath the table. Here is the ...

Guide to creating AngularJS directive attributes without a right-hand side in hiccup code?

I'm currently developing an AngularJS application using markup in hiccup format. Here is a snippet of the markup: <div modal-show modal-visible="showDialog" .........></div> Below is the corresponding Hiccup I have created: [:div.modal. ...

A method for dynamically enlarging a parent node within a dhtmlx tree using JSON data

As I was browsing through the dhtmlx documentation, I came across this particular method: This method determines how the server-side URL is constructed when making dynamic loading calls: <script> tree.setXMLAutoLoadingBehaviour(mode); </s ...

Difficulty installing Vue in Laravel

After attempting to install Vue.js within the Laravel framework, I noticed that it failed to create an asset folder or make any changes to the app.js file located inside the asset folder. Despite running `npm install` and `npm run watch`, when I checked ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...

Is it possible to integrate BottomNavigation with various components?

Struggling to implement a bottom navigation with TabContent from components. Despite the code below, the tab content does not display and no errors are thrown. PageContainer.vue: <template> <BottomNavigation selectedIndex="1" class="tab__cont ...

Issue with Vue2's v-text functionality

Recently, I've delved into Vue2 and encountered a problem with form submission and validation on a single page. The issue lies in the error display process – I want errors to be shown beneath each form input as soon as they occur, rather than waitin ...

Is there an equivalent of getElementById for placeholder text?

I need help automating the input of information on a webpage using JavaScript. Each field has a unique ID, like this: <div id="cc-container" class="field has-float-label"> <input placeholder="ccnumber" id="credit_card_number" maxlength="16" ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

Manipulate the value(s) of a multi-select form field

How can you effectively manage multiple selections in a form field like the one below and manipulate the selected options? <select class="items" multiple="multiple" size="5"> <option value="apple">apple</option> <option va ...

Utilize a function in module.exports that calls for a variable within the module

I am currently working on designing my modules in such a way that they don't need to be required multiple times. In my approach, I am passing arguments from the main app.js file to all of my modules. One of the modules I have is for user login and it ...