Deliver a modification of the injected variable

I am facing an issue where I provide variables in a component and then try to inject/change them in the child component. Surprisingly, this setup works perfectly fine on the local server but once uploaded to the live server, the variable doesn't seem to update.

I am utilizing the composition API for this project.

Parent Component A

import { provide, ref } from 'vue';

const loggedIn = ref(false);
provide('global', loggedIn);

const credentials = ref(true);
provide('credentials', credentials);

Child Component B

<script setup lang="ts">
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
} from "@ionic/vue";

import router from "@/router";

import { inject, ref } from "vue";

const global: boolean = inject("global") as boolean;

const credentials: boolean = inject("credentials") as boolean;


function greet(global: boolean, credentials: boolean) {
  
  const usr = document.querySelector("input[name=email]").value;

  const pass = document.querySelector("input[name=password]").value;
  if (
    usr === "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5433213127201433213127207a373b39">[email protected]</a>" &&
    pass === "guest123#"
  ) {
    
    this.global = true;

    this.credentials = false;

    router.push("/app");
  }
}


</script>

Both 'this.global = true' and 'this.credentials = false' are triggering warnings in VS Code:

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
HomePage.vue(19, 10): An outer value of 'this' is shadowed by this container.

Any suggestions or ideas on how I can resolve this particular issue?

Answer №1

  1. Injections do not have reactive behavior by default.

To make your injections reactive, you can utilize a computed property. For more information, refer to the Provide / Inject: Working with Reactivity section.

  1. Injections are similar to props and readonly.

You can modify the injected value in the child component, but this change will not be propagated to the parent component.

For further clarification, check out the provided Vue SFC Playground Example.

The recommended solution is to utilize a custom store or Vuex/Pinia.

You can also refer to the updated version of the SFC Playground.

The update to Message2 only reflects in the GrandChild component and not in the parent App.

Answer №2

In the world of Vue.js, a parent component has the ability to pass down a reference and an update function to its child components, as cleverly explained in the official Vue documentation.

const userAuthenticated = ref(false);
provide('appData', { userAuthenticated, updateUserAuthentication });

function updateUserAuthentication(newValue) { ... }

Subsequently, the child component can manipulate the reference value by simply invoking the provided update function handed down by its parent.

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

Tips for including vue-autonumeric in your webpack 2 setup

Encountering a problem while bundling the vue-autonumeric package with Webpack 2, where the dependency AutoNumeric is not being found properly. Although there is an alias set up in the configuration that works fine with webpack 3, it seems to fail when wo ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Node.js: Managing multiple occurrences of the same event name for testing purposes

When it comes to unit testing using mocha, I am looking for a way to set up an asynchronous queue for handling events. Previously, I used a once() Promise to wait for events like this: import EventEmitter from 'events' import { once } from ' ...

Prevent duplicate API calls in React with TypeScript

Upon page load, it is important to extract the value from the URL and send it to the API. However, due to changes in the state of parent objects, the API call is triggered three times when it should ideally only be called once. import React, {useContext ...

Enhancing Vue prop with TypeScript typing

In my Vue component, I am working with a prop called tabs. The format for this prop is expected to be as follows: [{ id: string title: string color: `#${string}` },{ id: string title: string color: `#${string}` }] Currently, I am utilizing Lar ...

Using Vuetify to submit form data using Axios

Utilizing Vuetify in my VueJs application, I am trying to send data from a form that includes file (CSV) uploads and various number inputs. My goal is to achieve this using Axios. Despite several attempts, I keep encountering a 404 error. This snippet sh ...

When Angular 5 is loaded, the select list on the page will automatically display the matching option that

I am currently working on a form that is read-only and showcases data retrieved upon loading the page. One of the sections in this form includes an IsActive dropdownlist with options True or False. I have set up my model property isActive to bind with the ...

Issue with IN operator functionality in TypeORM when used with MongoDB

My goal is to fetch a list of items using an array of IDs by utilizing the following code: import { In } from 'typeorm'; ...findBy({ _id: In(ids) }) The IDs are predefined upon creation: @Entity() export class Foo { @ObjectIdColumn({ generated ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

What exactly do `dispatch` and `commit` represent in vuex?

Recently, I came across a Typescript project in Vue.js with a Vuex store that had the following code: async getUserProfile ({ dispatch, commit }: any) {} I found working with any cumbersome as it doesn't provide helpful autocomplete features in the ...

Vue plugins that emit events

In the scenario where I have a basic Vue plugin that does not contain any components, but simply provides some methods to the user: export default { install(Vue, options) { // Unrelated tasks go here. } Vue.prototype.$foo = () => { ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

What is the best way to iterate through an Object.entry and multiply one value by another key value within a loop?

I am looking to enhance the functionality of my Vue.js composition API web application by calculating the total number of employed workers in different sectors. However, I want to multiply the number of workers by another key:value property instead of ju ...

Tips for conducting a worldwide search in Angular 2?

I'm currently navigating my way through angular2 development and I am aiming to conduct a comprehensive search within an array of JSON objects. To illustrate, consider this sample array: invoiceList = [ { invoiceNumber: 1234, invo ...

What is the best way to use a regex to filter the user's input in a Vuetify combobox and generate a chip?

I am working on implementing a restriction for a specific regex pattern while the user types in a combobox to add new chips, such as allowing only phone number chips. Complete Vue Source code: https://codesandbox.io/s/chips-so-0gp7g?file=/src/domains/ex ...

React-scripts is not recognizing tests that have the .tsx file extension

Currently in the process of converting my project to TypeScript, everything is almost working perfectly. The code builds without issues and renders correctly. The only hiccup I'm facing is with my tests. I've observed that when I change a test f ...

There was an issue while attempting to differentiate '[object Object]'. Ionic only allows arrays and iterables for this operation

I am looking for a way to extract all the "friend" objects from a JSON response and store them in an array so that I can iterate through them on an HTML webpage. ...