Currently utilizing vuejs 2.6.14 and encountering the following problem:
Changes made in child component are reflecting in parent component without using $emit in the code.
This is contrary to the typical scenario of updating data between parent and child components.
Below is a detailed overview of my code:
I have a parent component named Testing.vue, passing a JSON object ("userData") to a child component called GeneralData.vue.
This is what the parent component code looks like:
<template>
<div id="testing-compo">
<div style="margin-top: 1rem; margin-bottom: 1rem; max-width: 15rem">
<label
class="sr-only"
for="inline-form-input-username"
style="margin-top: 1rem; margin-bottom: 1rem"
>Account settings for :</label
>
<b-form-input
v-model="username"
id="inline-form-input-username"
placeholder="Username"
:state="usernameIsValid"
></b-form-input>
</div>
<b-button class="button" variant="outline-primary"
@click="callFakeUser">
Populate fake user
</b-button>
<GeneralData :userData="user" />
</div>
</template>
<script>
export default {
name: "Testing",
components: {
GeneralData,
},
data() {
return {
user: null,
username: null,
};
},
computed: {
usernameIsValid: function () {
if (this.username != null && this.username.length >= 4) {
return true;
} else if (this.username != null) {
return false;
}
return null;
},
},
methods: {
async callFakeUser() {
userServices.getFakeUser().then((res) => {
this.user = res;
console.log(this.user);
});
},
</script>
A straightforward testing component that calls userServices.getFakeUser(), which returns a JSON object asynchronously.
For the child component:
<template>
<div id="general-compo">
<!-- AGE -->
<div class="mt-2">
<label for="text-age">Age</label>
<div>
<b-form-input
v-model="userAge"
placeholder="+18 only"
class="w-25 p-1"
type="number"
>
</b-form-input>
</div>
</div>
<!-- LANGUAGES -->
<div class="mt-2">
<label for="lang-list-id">Language(s)</label>
<div
v-for="langKey in userLangsCount"
:key="langKey"
style="display: flex; flex-direction: row"
>
<b-form-input
readonly
:placeholder="userLangs[langKey - 1]"
style="max-width: 50%; margin-top: 0.5rem"
disabled
></b-form-input>
**This form is set to read only, for display purposes only**
<b-button
variant="outline-danger"
@click="removeLang(langKey)"
style="margin-top: 0.5rem; margin-left: 1rem"
>Remove</b-button
>
**This button removes a language from the userLangs array by calling removeLang(langKey)**
</div>
<div style="display: flex; flex-direction: row">
<b-form-input
v-model="userCurrentLang"
list="langlist-id"
placeholder="Add Language"
style="max-width: 50%; margin-top: 0.5rem"
></b-form-input>
<datalist id="langlist-id">
<option>Manual Option</option>
<option v-for="lang in langList" :key="lang.name">
{{ lang.name }}
</option>
</datalist>
<b-button
:disabled="addLangBtnDisabled"
variant="outline-primary"
@click="addLang()"
style="margin-top: 0.5rem; margin-left: 1rem"
>Add</b-button
>
</div>
</div>
</div>
</template>
<script>
import langList from "../assets/langList";
export default {
name: "GeneralData",
components: {},
props: {
userData: Object,
},
data() {
return {
userAge: null,
langList: langList,
userLangs: [],
userCurrentLang: null,
};
},
watch: {
//Updating tabs with fetched values
userData: function () {
this.userLangs = this.userData.general.langs;
this.userAge = this.userData.general.age
},
},
computed:
**userGeneral is supposed to represent the data equivalent of userData.general, it is therefore computed from the user input, its value is updated each time this.userAge or this.userLangs changes**
userGeneral: function () {
//user data in data() have been filled with userData values
return {
age: this.userAge,
langs: this.userLangs,
};
},
**returns the amount of languages spoken by the user to display them in a v-for loop**
userLangsCount: function () {
if (this.userLangs) {
return this.userLangs.length;
}
return 0;
},
**gets a list of languages name from the original JSON list for display purposes**
langNameList: function () {
let namelist = [];
for (let i = 0; i < this.langList.length; i++) {
namelist.push(langList[i].name);
}
return namelist;
},
**returns true or false depending on whether entered language is in original list**
addLangBtnDisabled: function () {
for (let i = 0; i < this.langList.length; i++) {
if (this.userCurrentLang == langList[i].name) {
return false;
}
}
return true;
},
},
methods: {
addLang() {
this.userLangs.push(this.userCurrentLang);
this.userCurrentLang = null;
},
removeLang(key) {
this.userLangs.splice(key - 1, 1);
},
}
}
</script>
Data displayed in the Vue.js dev tool after updating this.user in Testing.vue:
Data in Testing.vue :
user : {
general{"age":22,"langs":["French"]}
}
Data in GeneralData.vue :
userData : {
general:{"age":22,"langs":["French"]}
}
userAge : 22
userLangs : ["French"]
userGeneral :
{
general:{"age":22,"langs":["French"]}
}
Everything seems fine so far, right?
However, the issue arises when I change the age field in my form - userAge gets incremented, userGeneral.age gets updated, yet userData.general.age remains unchanged. This behavior is expected as userGeneral.age is computed based on this.userAge, and userData is a prop that should not be mutated according to best practices (and no method sets userData.general.age = xxx either).
Yet, if I click the Remove button next to French in the language list, this.userLangs gets updated as expected and becomes [], userGeneral.langs also gets updated to [], and surprisingly, userData.general.langs also gets updated to [] which doesn't make sense to me.
Even worse, in the parent component Testing.vue, user.general.langs is now also set to [].
Somehow, this.userLangs updated the prop this.userData, and this prop has updated its original sender user in the parent component, even though no $emit was used.
I do not want this behavior as it seems unintended and risky, and also because I plan to implement a 'save' button later to allow users to modify their values collectively.
Things I've tried: using various .prevent, .stop attributes on the @click element of the Remove/Add buttons, incorporating e.preventDefault in the methods, and modifying addLang and removeLang to include sending the $event parameter - none of these attempts resolved the issue.
Hopefully I didn't implement the .prevent part correctly, and someone can assist in preventing this unwanted reverse flow.