如何使用 Vue.js 异步组件?

问题描述 投票:0回答:5

我正在使用 Laravel 5.4 和 Vue.js 2。我想使用按钮异步加载组件。我的 Vue.js 组件是独立的:example.vuetest.vue,我将它们作为 HTML 标签加载。

这是我的app.js

import './bootstrap';
import example from './components/Example.vue';

Vue.component('example', example);

const app = new Vue({
    el: '#app'
});

这是展示组件的地方:

<How can I use Async components?div id="app">
     <example2></example2>
</div>

如何使用异步组件?


不,我想你不明白我的意思。这是我的组件注册:

import './bootstrap';
import example from './components/Example.vue';

Vue.component('example', example);

Vue.component('example2', function (resolve) {

    require(['./components/Example2.vue'],resolve)

})

const app = new Vue({
    el: '#app'
});

require 中,它默认为已解决(如图所示)。 我不知道当我调用组件时应该如何将解析和拒绝键传递给页面中的此方法。

vue.js vuejs2 async-components
5个回答
10
投票

您可以通过样式方式在 vue 2 中使用异步组件。正确使用异步组件可以减少项目加载时间。 您可以使用异步组件,如下所示:

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router ({
routes: [
  {
    path: '/',
    name:'LandingPage'
    component: () => import('@/containers/LandingPage.vue')
  },
  {
    path: '/login',
    name:'LoginPage'
    component: () => import('@/containers/LoginPage.vue')
  }
]
})

这种结构看起来更适合模板内的组件加载:

new Vue ({
  el: 'app',
    components: {
      AsyncComponent: () => import ('./AsyncComponent.vue')
    }
})

您可以查看:www.bdtunnel.com了解更多信息。


5
投票

根据 VueJs 上的文档,您可以从 2.3 版本开始定义这样的异步组件

const AsyncComp = () => ({
  // The component to load. Should be a Promise
  component: import('./MyComp.vue'),
  // A component to use while the async component is loading
  loading: LoadingComp,
  // A component to use if the load fails
  error: ErrorComp,
  // 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
})

您可以将其与内置组件结合使用来动态加载组件。

编辑:提到的文档的更新链接。


4
投票

对于 Vue.js 中的异步组件,resolve 参数是异步调用成功时调用的函数,因此您的 require() 调用需要位于被调用的解析函数内。您只需删除 require() 调用中的括号并按如下格式设置该行:

resolve(require('./components/Example2.vue'))

在下面的示例中,我们使用基本的

setTimeout()
来模拟异步调用。解析函数将在 5 秒后调用,并将
Example2
组件加载到应用程序中。

为了通过单击按钮显示/隐藏

Example2
组件,您必须在
data()
函数中添加反应数据属性。然后,如果您查看 App.vue 的模板,我们将使用
v-if
(https://v2.vuejs.org/v2/guide/conditional.html#v-if) 指令来添加/从虚拟 DOM 中删除
Example2
组件。您也可以在这里轻松使用
v-show
(https://v2.vuejs.org/v2/guide/conditional.html#v-show) 指令,尽管该组件会保留下来并被隐藏。您可以在此处阅读有关
v-if
v-show
的更多信息:https://v2.vuejs.org/v2/guide/conditional.html#v-if-vs-v-show。这是在应用程序中隐藏和显示模态框的一种非常常见的范例——下面的示例很好地展示了这一点:https://v2.vuejs.org/v2/examples/modal.html

main.js

import Vue from 'vue'
import App from './components/App.vue'

Vue.component('example2', function(resolve, reject) {
  setTimeout(function() {
    resolve(require('./components/Example2.vue'))
  }, 5000)
})

const app = new Vue({
  el: '#app',
  render: h => h(App)
})

示例2.vue

<template>
  <div>
    <div>Hello example 2!</div>
  </div>
</template>      

应用程序.vue

<template>
  <div id="app">
    <button type="button" @click="onButtonClick">Click me to add the example2 component</button>
    <example2 v-if="show_example2"></example2>
  </div>
</template>

<script>
  export default {
    name: 'app',
    data() {
      return {
        show_example2: false
      }
    },
    methods: {
      onButtonClick() {
        this.show_example2: true
      }
    }
  }
</script>

1
投票

我完成此类事情的一种方法是使用以下设置创建您的

example2
组件:

<template>
  <div>
    <div v-if="inited">
      <div>{{foo}}</div>
      <div>{{bar}}</div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        foo: '',
        bar: '',
        inited: false
      }
    },
    mounted() {
      var me = this
      axios.get('/my/ajax/call').then(function(response) {
        me.foo = response.data.foo
        me.bar = response.data.bar
        me.inited = true
      })
    }
  }
</script>

基本上,只要组件被安装,它就会渲染空信息,直到 AJAX 调用完成,然后响应式数据将被更新,Vue 将自动更新响应式数据元素。如果您不想在模板中显示其他标记或内容,则可以随时创建

inited: false
数据属性并在 AJAX 回调中将其设置为
true
,然后使用
:v-if="inited"
包装器上的 :v-show="inited"
指令
div
隐藏组件的内容,直到 AJAX 调用返回。


1
投票

Vue 3 - 重大变更

异步组件现在需要

defineAsyncComponent
辅助方法:

// vue 2.x
const asyncPage = () => import('./NextPage.vue')

// vue 3.x
const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))

另一个重大更改是,在定义附加选项时,

component
选项被重命名为
loader

const asyncPageWithOptions = defineAsyncComponent({
  loader: () => import('./NextPage.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
})

文档:https://v3-migration.vuejs.org/writing-changes/async-components.html#_3-x-syntax

© www.soinside.com 2019 - 2024. All rights reserved.