Vue 开发人员。现在我正在尝试 vuebnb 教程,并且遇到了路由和 mixins 的问题。我尝试在使用 beforeRouteEnter 保护进入路由器之前分配数据,但似乎我的模板是在数据分配之前呈现的。以下是我尝试过的代码。
列表页面.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>
路由-mixin.js
import axios from 'axios';
function getData(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');
getData(to).then((data) => {
next(component => {
component.assignData(data);
});
});
console.log('after_next');
}
};
这里的数据是一个对象,它就像{listing: {...}, images: Array(5), path: "/listing/1}。检查从服务器获取的数据。但是当我尝试渲染 ListingPage 时。 vue,错误在控制台中记录如下:*
[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>
不管错误如何,页面都显示成功。请帮我摆脱这个错误: