Assign Vue instance data to a non reactive variable - vue.js

I have a form that has a modal that I use to populate an array within the form. Every time the modal is submitted, I push the Vue object into an array that is on the main form. The problem I'm facing is that every item in the array is linked and when I edit one item, all the items in the array get edited.
data: {
myForm: {
form_element: null,
my_array: [],
},
modalForm: {
modalFormElement: null,
},
},
methods: {
addRow(){
this.myForm.my_array.push(this.modalForm);
},
},
Assigning this.modalForm to a variable first did not work.

This is a reference issue. The modalForm object (i.e this.modalForm) references the same place in memory. When you push this.modalForm into the array, changing the value of a property of the object will change the rest. To prevent this issue, copy the modalForm object before pushing it to the array.
data: {
...
modalForm: {
modalFormElement: null,
},
},
methods: {
addRow(){ //
this.myForm.my_array.push({...this.modalForm}); // shallow clone the object using the es2015 spread syntax
},
},
The following are other ways to clone objects in JavaScript, but I will stick to the es2015 spread syntax in my example. For more on javascript references for objects, see this

Related

why prop value is changing with data changes in vuejs3?

props that I'm getting
props : {
images : Object,
locale : String,
},
data method
data() {
return {
form : this.$inertia.form({
product_images : this.images.data,
}),
}
},
I'm updating project_images on click event like so
Add() {
this.form.product_images.push({image : null});
},
but here problem is that as project_images updated with a new object. it also updates the prop images(Add the object in the data field of images props like product_images). i don't want that prop should be changed because I'm using the old prop value. why is this strange thing happening?
JavaScript arrays are copied by reference, so form.product_images and images.data are referring to the same array in memory. Editing one variable would affect the other.
The solution is to deep copy the original array into a new array. One way to do that is to map the array into newly spread objects:
data() {
return {
form : this.$inertia.form({
product_images : this.images.data.map(x => ({...x})),
}),
}
},

vue unexpected reactivity from props

I just noticed an unexpected behaviour and now I don't know if it is normal or not.
I have a component named follows and a child component named follow-list-modal
I'm passing a followList (pagination ) from follows to its child component follow-list-modal
In the follow-list-modal I store the paginated array in the variable members
Follows.vue
<template>
<div>
<follow-list-modal
:follow-list="dataset">
</follow-list-modal>
</div>
</template>
<script>
export default {
props: {
dataset: {
type: Object,
default: {},
},
},
}
</script>
FollowListModal.vue
<template>
<div>
<button #click="fetchMore"> More </button>
</div>
</template>
<script>
export default {
props: {
followList: {
type: Object,
default: {},
},
data() {
return {
members: this.followList.data,
dataset: this.followList,
};
},
methods: {
fetchMore() {
let nextPage = parseInt(this.dataset.current_page) + 1;
axios
.get(this.dataset.path + '?page=' + nextPage)
.then(({ data }) => this.refresh(data))
.catch((error) => console.log(error));
}
},
refresh(paginatedCollection) {
this.dataset = paginatedCollection;
this.members = this.members.concat(...paginatedCollection.data);
},
}
When I click the button More in the follow-list-modal to get more data, I then want to append the new data to the members array.
The unexpected behaviour ( for me at least ). is that if I use push in the refresh method
this.members.push(..paginatedCollection.data);
It appends data not only to members but also to followList which is data that comes from the parent component follows
But if I use concat instead of push, it appends data only to members variable and not to followList
this.members = this.members.concat(..paginatedCollection.data);
Is this behaviour normal ?
I don't get why the followList changes when the members variable changes, I thought that reactivity is one way.
In other words, the members changes when the followList changes, but not the other way around
P.S I don't emit any events from follow-list-modal to follows or change the data of the follows component in any way from the follow-list-modal
In JavaScript, the properties of an Object that are also Objects themselves, are passed by reference, and not by value. Or you might say that they are shallow copied.
Thus, in your example, this.members and this.followList.data are pointing to the same variable in memory.
So, if you mutate this.members, it will mutate this.followList.data as well.
You could avoid this by doing a deep copy of the objects. The easiest method, and arguably the fastest, would be to use JSON.parse(JSON.stringify(obj)), but look at this answer for more examples.
data() {
return {
members: [],
dataset: [],
};
},
created() {
this.members = JSON.parse(JSON.stringify(this.followList.data));
this.dataset = JSON.parse(JSON.stringify(this.followList));
}
You instantiate your data with a direct link to the (initially undefined) property of your prop. This property is a complex entity like an Object (Arrays are Objects), and is thus called via reference. Since members references the same thing in memory as followList.data, when you're calling members, it will follow the reference to the same entity as followList.data. This doesn't have to do with Vue2 reactivity, but here's a link nontheless.
push mutates the array it is called on; it will follow the reference through members and change followList.data, updating its value when called through followList as well. Because the data key is not present on instantiation of the component, Vue can't watch it (just like you need to use Vue.set when adding a new key to a data object).
concat returns a new array of merged elements, and then replaces
the reference in members with the new array. Therefore from this point on you'll
no longer mutate followList.data, even with a push, as the reference has changed to a new entity.
When trying to set your initial members and dataset, I suggest using an initialization method that creates a clone of your followList and writes that to dataset, and running this on the created() or mounted() hook of your component lifecycle. Then create a computed property for members, no need to store followList.data thrice and potentially have dataset and members diverge.

UI not updating when nested array property value deleted, only when added

I have a page where an object with nested array values are passed in from the parent component. The user can then, using a series of events and components manage the data in these subscriptions. Currently I'm facing an issue where when a subscriptionId is removed from the props, conditions on the page aren't changing, but they do when it's added.
Child Component
export default {
props: {
// Format of this object is:
// { "gameId": [
// 'subscriptionId',
// 'subscriptionId',
// ] }
subscriptions: {
type: Object,
required: true
}
},
watch: {
subscriptions: {
handler: function (newSubscriptions, oldSubscriptions) {
// NEVER gets fired when `subscriptionId` deleted from array list, but is fired when a new subscription is added
console.log('handler');
}
},
deep: true
}
},
I suspect this might be related to how I'm removing the array from the object. Essentially I'm copying the array, deleting the index in question and overwriting the original array. My hope with this approach is that the watcher wouldn't be needed but it appears to have no impact. Here's the code that exists on the parent component to update the subscriptions:
Parent Component
// Works great, don't have any issues here
handleSubscribed (subscriptionId) {
let newSubscriptions = [subscriptionId];
if (this.subscriptions.hasOwnProperty(this.currentGame.id)) {
newSubscriptions = this.subscriptions[this.currentGame.id];
newSubscriptions.push(subscriptionId);
}
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
},
handleUnsubscribed (subscriptionId) {
// if there's more than one, delete only the one we're looking for
if (this.subscriptions.hasOwnProperty(this.currentGame.id) && this.subscriptions[this.currentGame.id].length > 1) {
let newSubscriptions = this.subscriptions[this.currentGame.id];
delete newSubscriptions[newChannels.indexOf(subscriptionId)];
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
// shows my subscription has been removed, but GUI doesn't reflect the change
console.log('remove-game', newSubscriptions);
return;
}
this.$delete(this.subscriptions, this.currentGame.id);
},
I was hoping watch might be the solution, but it's not. I've looked over the reactive docs several times and don't see a reason for why this wouldn't work.
VueJS version: 2.5.7
Use Vue.delete instead of the delete keyword.
The object is no longer observable when using delete, therefore not reactive.
Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

vuejs computed setter of given prop is not reactive

I'm using computed to copy my prop value and use/mutate it in my component:
export default {
props: ['propOffer'],
computed: {
offer: {
get: function () {
return JSON.parse(JSON.stringify(this.propOffer))
},
set: function () {
this.offer
}
},
}
The problem is within using setter. It is not reactive. When I use some kind of input, there is a delay, so my computed offer isn't updating instantly. Example of input:
<v-text-field
label="Offer title"
v-model="offer.title"
></v-text-field>
This is far opposite to the behaviour when I declare offer as a variable (wthout computed) - then I got my {{offer}} changes instantly inside the <template>
How can I improve it? Am I setting my computed wrong?
To better understand this situation, this is what happens at the moment:
When the application loads, the initial state is:
<your-component>
propOffer: '{"title":"test"}'
offer.<lastValue>: undefined
At the point in time, your application will load the v-text-field, this references field offer, and this inits the offer computed variable:
<your-component>
propOffer: '{"title":"test"}'
offer.<lastValue>: [Javascript object 1]
[Javascript object 1]
title: "test"
<v-text-field>
value: "test"
As the user types into the v-text-field, its value changes, because the v-model emits back updates:
<your-component>
propOffer: '{"title":"test"}'
offer.<lastValue>: [Javascript object 1]
[Javascript object 1]
title: "test123"
<v-text-field>
value: "test123"
As you can see here, the setter is never invoked in the normal operation, and hence your code to save it does not run.
You can solve this by making another computed prop for the title of the offer, and then adding some code to prevent your changes from being made undone.
Let's start with the getter & setter for the title:
computed: {
title: {
get() {
return this.offer.title;
},
set(title) {
this.offer = {...this.offer, title};
}
},
// ....
Now we need to properly handle this set operation inside our main offer function, because if we don't handle it, and basically modify its returned object, we get into the territory of undefined behaviour, as the value of the computation doesn't match the computation.
// ...
offer: {
get: function () {
if (this.modifiedOffer) {
return this.modifiedOffer;
}
return JSON.parse(JSON.stringify(this.propOffer))
},
set: function (offer) {
this.modifiedOffer = offer;
}
},
},
data() {
return: {
modifiedOffer: undefined,
};
},
After doing this pattern, you now have a stable application, that shows no undefined behaviour, for more functionality, you basicly need to check if the propOffer changes, and either forcefully delete the this.modifiedOffer, or add more logic to a different computed variable that informs the user there is a data conflict, and ask him to overwrite his data.

VueJS2: Update data pattern?

So, in one of my VueJS templates, I have a left sidebar that generates buttons by iterating (v-for) through a multidimensional items array.
When one of these buttons is clicked, a method is run:
this.active.notes = item.notes
active.notes is bound to a textarea in the right content section.
So, every time you click one of the item buttons, you see the (active) notes associated with that item.
I want to be able to have the user edit the active notes in the textarea. I have an AJAX call on textarea blur which updates the db. But the problem is, the items data hasn't changed. So if I click a different item, then click back to the edited item, I see the pre-edited notes. When I refresh the page, of course, everything lines up perfectly.
What is the best way to update the items data, so that it is always consistent with the textarea edits? Should I reload the items data somehow (with another AJAX call to the db)? Or is there a better way to bind the models together?
Here is the JS:
export default {
mounted () {
this.loadItems();
},
data() {
return {
items: [],
active: {
notes: ''
},
}
},
methods: {
loadItems() {
axios.get('/api/items/'+this.id)
.then(resp => {
this.items = resp.data
})
},
saveNotes () {
...api call to save in db...
},
updateActive (item) {
this.active.notes = item.notes;
},
}
}
i can't find items property in your data object.
a property must be present in the data object in order for Vue to convert it and make it reactive
Vue does not allow dynamically adding new root-level reactive properties to an already created instance
maybe you can have a look at this:
Vue Reactivity in Depth
It doesn't seem like this.items exists in your structure, unless there is something that isn't shown. If it doesn't exist set it as an empty array, which will be filled on your ajax call:
data() {
return {
active: {
notes: ''
},
items: [],
},
Now when you ajax method runs, the empty array, items, will be filled with your resp.data via this line:(this.items = resp.data). Then you should be able to iterate through your items array using v-for and your updateActive method should work as you intend it to.
use PUSH
this.items.push(resp.data);
here is a similar question
vue.js http get web api url render list