Getting the value of an injected variable in a Vue.js computed method

I have utilized the provide/inject mechanism to pass data from a parent component to its grandchildren. However, in one of my components, I need to manipulate the data before rendering it in the template.

My current setup looks like this:

export default defineComponent({
  name: 'MrComponent',
  inject: ["mydata"],
  computed: {
    processedData() {
      const mydata = this.mydata;
      return mydata + 1; // Perform some data manipulation here
    }
  }
})

Unfortunately, I am encountering the following error:

[vue-cli-service] TS2339: Property 'mydata' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: ((...args: never) => any) | undefined; }, { chartOptions: { responsive: boolean; maintainAspectRatio: boolean; cutout: string; borderWidth: number; }; }, ... 15 more ..., {}>'.
[vue-cli-service]   Property 'mydata' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: { [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: ((...args: never) => any) | undefined; }; ... 10 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHan...'.
[vue-cli-service]     41 |   computed: {
[vue-cli-service]     42 |     chartData() {
[vue-cli-service]   > 43 |       const mydata = this.mydata;
[vue-cli-service]        |                           ^^^^^^^^
[vue-cli-service]     44 |     }
[vue-cli-service]     45 |   }
[vue-cli-service]     46 | })

Although accessing mydata directly in the template works fine:

<template>
{{ mydata }}
</template>

I require additional processing steps before displaying the data. What would be the appropriate approach in this scenario?

Thank you.

Answer №1

It appears that there may be a potential Vue bug in this scenario, where the prop should ideally be detected automatically from the 'inject' option (referenced in vuejs/core#5931). However, there are a few workaround solutions available...

Approach 1: Simulate prop type in 'defineComponent'

If your component does not have any 'props', you can simulate a 'mydata' prop by explicitly specifying it in the first type argument of 'defineComponent()':

export default defineComponent<{ mydata: number }>({
  inject: ['mydata'],
  computed: {
    processedData() {
      // Accessing 'this.mydata' as a number here
    }
  }
})

However, please note that this workaround is delicate and may cause issues when adding the 'props' option later on.

Approach 2: Implement Composition API

Migrate the relevant sections of your code to utilize the Composition API (specifically, use of inject() and computed()):

import { defineComponent, inject, computed } from 'vue'

export default defineComponent({
  setup() {
    const mydata = inject('mydata') as number
    const processedData = computed(() => {
      return mydata + 1
    })

    return {
      processedData
    }
  }
})

Answer №2

Are you in search of information about Utility Types - ComponentCustomProperties?

declare module 'vue' {
  interface ComponentCustomProperties  {
    fastdata: {
      user: {
        name: string,
        phone: string,
        points: number,
        level: number,
        next_level: number,
        total_kg: number,
        collection: Array<any>,
      },
      news: Array<any>,
    },
  }
}

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

Using Flask to pass variable data from one route to another in Python using the `url

I am facing an issue with sending a variable value to Python from Flask HTML/JS via url_for(). Here's my Python code: @app.route('/video_feed/<device>') def video_feed(device): # return the response generated along with the speci ...

The website at 'https://example.com' was successfully loaded using HTTPS, but there is a request for an insecure XMLHttpRequest Endpoint

Mixed Content Warning: The webpage at '' loaded securely via HTTPS, but attempted to access an insecure XMLHttpRequest endpoint ''. This request has been blocked as it needs to be served over a secure connection (HTTPS). ...

Tips for applying a jQuery class when the page is both scrolled and clicked

As I work on building a HTML website, I encountered an interesting challenge. I want to create a dynamic feature where, as users scroll through the page, certain sections are highlighted in the navigation menu based on their view. While I have managed to a ...

Adjust the minimum date of the second datepicker to be one day after the selected date from the first datepicker

I am currently using Materializecss and working on developing a hotel reservation system. My goal is to have the DateOut Datepicker's minimum date set to 1 day ahead of the selected date in the DateIn Datepicker. Initially, this functionality works as ...

When I leave an input empty in JSX, my 'required' attribute does not work properly

Currently, I am working on a register.jsx file, but I am encountering an issue where clicking the button still triggers functionality even when the input fields are empty or undefined. I have reviewed my code multiple times and cannot identify any syntax ...

Troubleshooting Vue.js devtools not functioning correctly in an Electron Vue project

Whenever I launch the project using npm run electron:serve, I encounter an issue where the components tree of the Vue.js devtools and other tabs appear empty. It seems like the project is not being detected properly. Is there a solution to resolve this pr ...

How can pagination be implemented with a line chart in Chart.js?

I'm dealing with a large amount of data - around 10,000 rows that I need to display in a line chart. I'm looking for a pagination system where users can click on an arrow to show the next 20 data points, and so on. Currently, my app crashes when ...

Is it possible to translate the IIFE functions of threejs into ES6 format?

I'm currently facing a challenge in breaking down my threejs project into smaller modules. One specific function that I'm struggling with is the following: var updateCamera = (function() { var euler = new THREE.Euler( 0, 0, 0, 'YXZ&apos ...

Looking for tips on programmatically adjusting the row count in a react table? Calling all React developers!

Currently, I have a table that is displaying data from an APP_DATA object. However, I am looking to add a column showing the number of rows dynamically next to each row. How can I achieve this? Keep in mind, only "prt" and "cat" are arrays, so you can onl ...

Scene lighting is now impacted by changes to the environment map in the latest r131 update

In my latest project, I am showcasing various models in a general scene. These models are created with different materials such as MeshPhongMaterial, MeshStandardMaterial, or sometimes both. The scene is illuminated by an AmbientLight and a DirectionalLig ...

Cause a malfunction in the triggering function of jQuery

$(document).ready(function(){ jQuery("#but1").bind("click",function(e){ alert(e.name); }); jQuery("#but1").trigger({name:'Dmy', surname:'My'}); }); The information doesn't seem to be getting passed correctly a ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

What is the best way to implement an onChange handler for React-Select using TypeScript?

I am struggling to properly type the onchange function. I have created a handler function, but TypeScript keeps flagging a type mismatch issue. Here is my function: private handleChange(options: Array<{label: string, value: number}>) { } Typescrip ...

Display a pop-up alert message when the session expires without the need to manually refresh the page

I have a query regarding the automatic display of an alert message. Even though I have set the time limit to 10 seconds, I still need to manually refresh the page for the alert message to appear. The alert message should notify the user that the session ...

console fails to return a function even when it is defined

After clicking the "stopCrash" button, I want the function backAgain to be executed 2 seconds later. However, I am encountering an error in the console: Uncaught TypeError: this.backAgain is not a function. Do you have any suggestions on how to fix this i ...

Vue multiselect is failing to retrieve the ID and name properties

While implementing the vue multiselect in my form, I customized the options to enable autocomplete functionality using axios post. However, despite returning only the id and name from the controller to the js file, all the properties of the option are bein ...

What is the process for adding a personalized button tag within rows using material-table and TypeScript, and what specific properties does it anticipate receiving?

Hey, I have a few questions that I could use some help with :) I'm trying to add both an Avatar tag and an Edit Button to every row in my table, but the Edit Button appears on both. How can I move the action to the right side of the table? Also, how d ...

Vuejs is throwing an error claiming that a property is undefined, even though the

I have created a Vue component that displays server connection data in a simple format: <template> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="page-header"> < ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...