Within my Vue.js application, I've created a method to update the src
attribute of images whenever a file is chosen from a file
input field. This method is triggered like so:
<input type="file" accept=".jpg,.png" @change="updateSrc($event, 'profile.photo.path')">
<img :src="profile.photo.path">
Here is the implementation of the method:
let app = new Vue({
el: "#app",
data: {
profile: {
photo: {
path: "images/profile/no-photo.png"
},
}
},
methods: {
updateSrc: function (event, srcPropertyName) {
let reader = new FileReader();
reader.onload = readerEvent => {
srcPropertyName.split(".").reduce((previousValue, currentValue, index, array) => {
if (index === array.length - 1) {
previousValue[currentValue] = readerEvent.target.result;
}
return previousValue[currentValue];
}, this);
};
reader.readAsDataURL(event.target.files[0]);
},
},
});
While this method works flawlessly, I've been contemplating whether there is a simpler way to update a nested property in Vue.js without resorting to tricks like using array.reduce()
. Is there a more straightforward approach to achieve this?
app.$set("profile.photo.path", "james.jpg");
It's clear that the above code snippet won't work. So, I'm left wondering if there is a direct solution to this.