In Vue3, I utilize the Provide and Inject feature to handle data changes without triggering a visual update. Instead, I apply a filter() function to remove an item from an

I am currently testing the usage of the provide and inject methods. I have placed the datas and del-function in the parent component to provide, and in the child component, I am dynamically rendering using v-for='data' in datas.

The objective I aim to achieve is: when the "delete button" is pressed, triggering the del-function in the child component should result in an item being deleted from the datas in the parent component, causing the datas provided to update.

Subsequently, the child component receives the updated datas to trigger a visual update, causing a re-render of the v-for. [!!!]

However, upon clicking the "delete button", the datas are updated internally, but visually, no items appear to be deleted.

View rendered cards using v-for

// Parent Vue file
<template>
  <Reslist/>
</template>

<script>

import Reslist from './components/ResList.vue'

export default {
  name: "App",
  components: {
     Reslist
  },
  provide() {
    return {
      datas: this.datas,
      delData: this.delData,
    };
  },
  data() {
    return {
      datas: [
        {
          id: 1,
          name: "wawa",
          age: "18",
        },
        {
          id: 2,
          name: "wmmmfwa",
          age: "1128",
       },
      ],
    };
   },
  methods: {
    delData(id) {
      console.log('delete-id ='+ id);
      const newDatas = this.datas.filter( element => element.id !== id);
      this.datas = newDatas;
      console.log(this.datas);

    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>



// Child Vue file
<template>
   <div v-for='data in datas' :key="data.name">
        <h2>{{data.name}}</h2>
        <p>{{data.age}}</p>
        <button @click='delData(data.id)'>delete</button>
   </div>
</template>
<script>
export default {
    inject:['datas','delData']
}
</script>
<style scoped>
div{
    width: 18.75rem;
    margin: 1.25rem auto;
    border: solid 1px grey;
    padding: 1.25rem;
}
</style>

I understand how to use props to pass data to a child component. My query lies in understanding why [provide and inject] do not function as expected. In the [provide] method, I have already set [datas = this.datas], so I am questioning if my logic contains any errors?

Answer №1

Hey there, buddy!

I managed to find a solution by utilizing computed properties...

I hope you find it useful!

Vue Parent File

<template>
  <Reslist/>
</template>

<script>
import Reslist from './ResList.vue'
import { computed } from '@vue/reactivity'
export default {
  name: "App",
  components: {
     Reslist
  },
  provide() {
    return {
      datas: computed(() => this.datas),
      delData: this.delData,
    };
  },
  data() {
    return {
      datas: [
        {
          id: 1,
          name: "wawa",
          age: "18",
        },
        {
          id: 2,
          name: "wmmmfwa",
          age: "1128",
        },
      ],
    };
  },
  methods: {
    delData(id) {
      console.log('delete-id ='+ id);
      const newDatas = this.datas.filter( element => element.id !== id);
      this.datas = newDatas;
      console.log(this.datas);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Child Vue File

<template>
   <div v-for='data in datas' :key="data.name">
        <h2>{{data.name}}</h2>
        <p>{{data.age}}</p>
        <button @click='delData(data.id)'>delete</button>
   </div>
</template>
<script>
export default {
  inject:['datas','delData']
}
</script>
<style scoped>
div{
    width: 18.75rem;
    margin: 1.25rem auto;
    border: solid 1px grey;
    padding: 1.25rem;
}
</style>

Setting up Main.js for Computed Properties

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
app.config.unwrapInjectedRef = true
app.mount('#app')

For more information on this configuration check out: https://vuejs.org/guide/components/provide-inject.html#working-with-reactivity

Answer №2

Your supplied data is not functioning reactively, and according to the Vue.js Documentation, for injected data to behave in a reactive manner, it needs to be provided as a computed property by enclosing it within a computed() function:

https://i.sstatic.net/CR5AV.jpg

This rule states:

Working with Reactivity

To ensure that injections are reactively linked to the provider, a computed property must be provided using the computed() function.

In your scenario, this implementation could resemble the following:

  provide() {
    return {
      datas: computed(() => this.datas),
      delData: this.delData,
    };
  },

With that being said, Vue continually receives updates, improvements, and bug fixes, and in order for complete functionality, it's necessary to incorporate an additional configuration temporarily into your application:

https://i.sstatic.net/sy5xj.jpg

This guideline mentions:

Temporary Config Required

The specified usage involves setting

app.config.unwrapInjectedRef = true
to automatically unwrap computed refs in injected data. This feature will be enabled by default in Vue 3.3, and for now, the config serves as a temporary measure to prevent issues. It will no longer be mandatory post 3.3 release.

Practically, this can be achieved as follows:

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

const app = createApp(App);
app.config.unwrapInjectedRef = true;

app.mount('#app')

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

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

What is the best way to display two tables side by side in a Vue component?

I am working on a vue application with a photo collection feature. My goal is to display the photos in two tables per row, iterating through the entire collection. Here's an example of what I'm aiming for: <row> &l ...

Adjust parent div size based on image size increase

I am currently facing a situation where I have a page displaying an image, but sometimes it appears too small. In order to make the image larger, I have utilized CSS Transform and it is working well. However, the issue lies in the fact that the parent DIV ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

Preserving text input with line breaks in a MERN Stack application

Can you help with saving multiple paragraphs in MongoDB? I have a textarea where users can input multiple paragraphs, but the line space is not being saved correctly in the database. Here is how I want the submitted data to look: Lorem ipsum dolor sit am ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

How can I attach an event listener to an element that is added dynamically with jQuery?

I added a new div element dynamically using jQuery's on method. However, I'm having trouble getting a listener to work for the newly created element. HTML <input class="123" type="button" value="button" /> <input class="123" type="butt ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

The function this.someFunction does not exist

Even though I have gone through the details of the bind requirement for methods to be associated with a React ES6 class, I am still facing challenges with this specific example: class ProductList extends React.Component { constructor(props) { super( ...

What is the best way to integrate a backend with the webpack template?

Recently diving into Vue.js and Webpack, I have decided to utilize the webpack template provided by vue-cli for my new project. Now that I have generated this project, I am interested in incorporating a backend system. I'm wondering if it would be wi ...

Vue CLI webpack causing image loading issues

What task am I currently working on? I am utilizing the intersection observer API to implement lazy loading functionality. What experiments have I conducted? I have tested the code on a basic HTML page and it functions flawlessly. However, when I incorpo ...

Is it possible for an Express app.get() function to identify and handle requests for specific file extensions

Is it possible for me to manage requests for any .html file type? For example, can I achieve something like this: // server.js app.get('/*.html', (req, res) => { // perform certain actions when an html file request is made }); ...

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

The issue with the Woocommerce quantity increment buttons not functioning properly persists after an AJAX refresh, and the automatic load feature only activates after two

I've hit a brick wall with this particular issue. Many people have suggested solutions, but none seem to be effective for me. My situation probably resonates with quite a few individuals: I decided to customize the WooCommerce quantity input (/global ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Implementing image loading within an accordion component using React and Material UI

I'm working with a React Accordion component using Material UI. Each time I open a tab in the Accordion, I want to load different images from another div that is located outside of the Accordion. Here is the current code snippet: export default funct ...