Calling all Vue developers! I am currently working on a vuebnb tutorial and running into an issue with routing and mixins. I have attempted to assign data before entering the router using the beforeRouteEnter guard, but it seems like my template is being rendered before the data is assigned. Below is the code snippet I have been trying:
ListingPage.vue
<template>
<div>
<img :src="'/' + images[1].img_path" />
</div>
</template>
<script>
import { populateAmenitiesAndPrices } from "../js/helpers";
import routeMixin from '../js/route-mixin';
export default {
mixins: [ routeMixin ],
data() {
return {
title: null,
about: null,
address: null,
amenities: [],
prices: [],
images:[],
}
},
methods: {
assignData({ listing, images }) {
console.log('inside_component_before_assign');
this.images = [...images];
Object.assign(this.$data, populateAmenitiesAndPrices(listing));
console.log('inside_component_after_assign');
}
},
components: {
}
};
</script>
route-mixin.js
import axios from 'axios';
function fetchData(to) {
return new Promise((resolve) => {
let serverData = JSON.parse(window.vuebnb_data);
if (!serverData.path || to.path !== serverData.path) {
axios.get(`/api${to.path}`)
.then(({ data }) => {
resolve(data);
});
} else {
resolve(serverData);
}
});
}
export default {
beforeRouteEnter: (to, from, next) => {
console.log('before_next');
fetchData(to)
.then((data) => {
next(component => {
component.assignData(data);
});
});
console.log('after_next');
}
};
In the above code snippet, the data object has structure like {listing: {...}, images: Array(5), path: "/listing/1}. Server data fetching is validated. However, upon rendering ListingPage.vue, an error is thrown in the console: *
[Vue warn]: Error in render: "TypeError: Cannot read property 'img_path' of undefined"
found in
---> <ListingPage> at resources/assets/components/ListingPage.vue
<App> at resources/assets/components/App.vue
<Root>
The page still displays successfully despite the error. Any assistance on resolving this error would be greatly appreciated. Thank you!