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?