等到父组件已装入/准备好,然后在vue.js中呈现子级

时间:2018-02-13 12:31:04

标签: javascript vue.js vue-router

在我的SPA应用程序中,我有一个<app-view>包装器,用于处理基本应用程序代码(加载用户数据,渲染导航栏和页脚等),并有一个slot用于呈现实际页面。仅当用户数据可用时才会呈现此广告位

创建此包装器是因为某些页面需要不同的基本代码,因此我无法将此基本代码保留在包含<router-view>的主应用程序中。

我试着查看vue-router是否提供高级选项或建议切换基本代码的设计模式,没有找到任何东西。

问题是子组件将在安装父组件之前呈现,即在父组件决定不呈现子组件之前(因为它正在加载用户数据)。这会导致undefined as no attribute foo等错误。

正因为如此,我正在寻找一种方法来推迟子渲染,直到它的父元素被挂载。

4 个答案:

答案 0 :(得分:1)

尝试了几个选项之后,看起来我需要咬紧牙关并明确定义我的组件所依赖的数据,如下所示:

<app-view>
  <div v-if='currentProfile'>
    ...
  </div>
</div>

(从{vuex store getter]收到currentProfile,并在app-view内提取

答案 1 :(得分:0)

您实际上可以将v-if放在组件中的<slot>标记上。

&#13;
&#13;
new Vue({
  el: '#app',
  render: function(createElement) {
    return createElement(
      // Your application spec here
      {
        template: `<slotty :show="showSlot"><span> here</span></slotty>`,
        data() {
          return {
            showSlot: false
          }
        },
        components: {
          slotty: {
            template: `<div>Hiding slot<slot v-if="show"></slot>.</div>`,
            props: ['show']
          }
        },
        mounted() {
          setTimeout(() => this.showSlot = true, 1500);
        }
      }
    );
  }
})
&#13;
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尽管没有SPA,但我也遇到类似的问题。我有一些子组件,它们需要来自父组件的数据。问题在于,只有在父级完成安装后才生成数据,因此我最终在子级中得到了空值。

这就是我解决的方法。我仅在父级完成安装后才使用v-if指令来安装子级。 (在mounted()方法中)请参见下面的示例

<template>
  <child-component v-if="isMounted"></child-component>
</template>
<script>
  data() {
     isMounted: false
  }, mounted() {
     this.isMounted = true
  }
</script>

之后,孩子可以从父母那里获取数据。 它有点无关,但是我希望它能给您一个想法。 在投票之前三思。

答案 3 :(得分:0)

对于想要在父组件从 API 调用中获取数据后立即显示子组件的任何人,您应该使用以下内容:

<template>
  <child-component v-if="itemsLoaded"></child-component>
</template>

<script>
  data() {
     itemsLoaded: false
  },
  methods: {
      getData() {
          this.$axios
              .get('/path/to/endpoint')
              .then((data) => {
                  // do whatever you need to do with received data
                  
                  // change the bool value here
                  this.itemsLoaded = true
          })
          .catch((err) => {
              console.log(err)
          })
      },
  }, 
  mounted() {
     this.getData()

     // DONT change the bool value here; papa no kiss
     this.itemsLoaded = true
  }
</script>

如果你尝试改变this.itemsLoaded = true方法中的布尔值mounted(),调用getData()方法后,你会得到不一致的结果,因为你可能会也可能不会收到数据在 this.itemsLoaded = true 执行之前。