【问题标题】:VueJS: dynamic component loses it`s props after reloadingVueJS:动态组件在重新加载后丢失了它的道具
【发布时间】:2020-09-17 00:59:13
【问题描述】:

我有一个 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' 并将 item 参数传递给 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'
  ],
}

暂时有效,但是当我重新加载页面时,所有内容都消失了,并且所有项目的值都未定义

重新加载后我应该如何让它工作?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    通过路由参数传递复杂对象仅在内存中有效。重新加载页面后,您拥有的唯一数据就是来自 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>
    

    在上面,我假设您的路线将参数作为道具传递。如果没有,请参阅https://router.vuejs.org/guide/essentials/passing-props.html

    【讨论】:

    • 谢谢,看来是个不错的解决方案;唯一知道的事情是我是否可以从搜索栏中获得 /:slug 或者它会是 404?
    • 对不起,我不知道这是什么意思
    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2022-11-19
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多