【问题标题】:vue async load component on clickvue 异步加载组件点击
【发布时间】:2019-02-13 02:46:14
【问题描述】:

我正在尝试在 Vue.js 中创建一个包含嵌套组件的组件。 结构可以简化为

ParentComponent.vue
|
|__ ChildComponent.vue

只有当我在 ParentComponent 中使用 @click 单击按钮时,是否可以获得 ChildComponent ?我希望组件仅在单击事件后才加载其文件,而不仅仅是显示/隐藏组件,因为我正在尝试优化网络使用并且嵌套可能会更深。

编辑: 我尝试了以下代码

<template>
  <div class="home">
    <button type="button" @click="isActive=!isActive">SHOW</button>
    <async-component v-show="isActive"></async-component>
  </div>
</template>

<script>

const AsyncComponent = () => ({
  // The component to load (should be a Promise)
  component: import('./components/ChildComponent.vue'),
  // A component to use while the async component is loading
  loading: LoadingComponent,
  // A component to use if the load fails
  error: ErrorComponent,
  // Delay before showing the loading component. Default: 200ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000
})

export default {
  name: "home",
  components: {
    AsyncComponent
  },
  data(){
    return{
      isActive:false
    }
  }
};
</script>

但是当我单击按钮时,它会显示组件,当我在开发人员工具中检查网络选项卡时,它不会显示如果获取任何内容并且组件已经加载,它只会显示/隐藏它。

【问题讨论】:

  • 你读过这个吗:Async Components?您是否尝试将其用于点击处理程序?请添加显示您尝试过的代码。
  • 我编辑了帖子并添加了我正在测试的代码,我已经阅读了链接并在页面末尾使用了 sn-p。

标签: javascript vue.js


【解决方案1】:

正如评论中提到的,这篇文章是一个很好的资源。不过,我会强调最重要的部分。

如果你是一个 Browserify 用户,想要使用异步组件,不幸的是它的创建者明确表示异步加载“不是 Browserify 永远支持的东西”。至少在官方上是这样。 Browserify 社区发现了一些变通方法,它们可能对现有的复杂应用程序有所帮​​助。对于所有其他场景,我们建议使用 Webpack 来获得内置的一流异步支持。

简而言之,如果您使用的是 browserify,则不能,因为您使用的是 SFC,所以我假设您是。

您还使用v-show,它使用隐藏的显示类来隐藏,因此即使没有browserify,它也会在最初加载,因此您应该使用'v-if',它删除和添加元素,而不是切换可见性(您可以使用调试控制台检查)。

然而,一种可能性是代码拆分,browserify 会将组件代码拆分到一个单独的文件中,但这也可能没有您描述的结果。

示例:

const Menu = () => import(/* webpackChunkName: "signed-in" */ './pages/Menu');

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-05-15
  • 2019-03-24
  • 2016-09-13
  • 2017-01-26
  • 2017-07-24
  • 2019-09-28
  • 1970-01-01
  • 2019-06-25
相关资源
最近更新 更多