我有一个django rest_framework作为服务器和vuejs作为客户端。有一个类似'/‘的索引页面,在这里我使用v-for来迭代一个对象数组,以显示一些物品的卡片。每个卡都有一个指向‘/info’的按钮(通过路由器中的/:slug动态更改),如下所示:
...
<RouterLink :to="{name: 'contentItemInfo', params: {item: item, slug: item.slug} }">
<button class="card-button btn fade-in">
...
</button>
</RouterLink>
...然后,当我们按下按钮时,我们将转到'/:slug‘并将项目参数传递给props,如下所示:
...
<video class="video" type="video/mp4" autoplay loop :src="item.trailer"/>
<h3 class="video-info-h3 px-5 py-1 rounded">{{ item.title }}</h3>
<h5 class="video-info-h5 px-5 py-1 rounded">{{ item.subtitle }}</h5>
<p class="video-info-p px-5 py-1 text-wrap rounded">{{ item.description }}</p>
...
export default {
name: "ContentItemInfo",
components: {Footer, Navbar},
props: [
'item'
],
}目前有效,但当我重新加载页面时,所有内容都消失了,所有项的值都没有定义
如何在重新加载后使其工作?
发布于 2020-09-17 09:16:06
通过路由参数传递复杂对象只能在内存中工作。重新加载页面后,您所拥有的唯一数据就是URL中的字符串。您必须从后端加载item数据才能加载新的页面。
尝试类似这样的操作,将item属性设为可选,如果未设置则加载数据
export default {
name: "ContentItemInfo",
components: {Footer, Navbar},
props: {
item: {
type: Object,
default: null
},
slug: String // set from the route param
}
data: vm => ({
video: vm.item // initialise a local copy so you can update it if required
}),
async created () {
if (this.video === null) {
// just guessing with this bit
const { data } = await axios.get(`/api/video-for-slug/${encodeURIComponent(this.slug)}`)
this.video = data
}
}
}和你的模板
<div v-if="video">
<video
class="video"
type="video/mp4"
autoplay
loop
:src="video.trailer"
/>
<h3 class="video-info-h3 px-5 py-1 rounded">{{ video.title }}</h3>
<h5 class="video-info-h5 px-5 py-1 rounded">{{ video.subtitle }}</h5>
<p class="video-info-p px-5 py-1 text-wrap rounded">{{ video.description }}</p>
</div>
<p v-else>Loading...</p>在上面的代码中,我假设你的路由把params作为道具来传递。如果不是,请参阅https://router.vuejs.org/guide/essentials/passing-props.html
https://stackoverflow.com/questions/63929824
复制相似问题