我如何使用Vue Async组件?

K1-*_*ria 8 vue.js async-components vuejs2

我正在使用laravel 5.4和vue 2,我想使用按钮将组件加载为异步.我的Vue js组件是独立的:example.vue和test.vue,我将它们加载为html标记.

这是我的app.js:

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

Vue.component('example', example);

const app = new Vue({
el: '#app'
});
Run Code Online (Sandbox Code Playgroud)

这是展示组件的地方

    <How can i use Async components?div id="app">
         <example2></example2> 
    </div>
Run Code Online (Sandbox Code Playgroud)

我如何使用Async组件?


不,我想你不理解我.这是我的组件注册

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'
});
Run Code Online (Sandbox Code Playgroud)

并且在require中,它默认已解析(如显示)我不知道在调用组件时如何在我的页面中传递解析并拒绝此方法的键.

Suk*_*ala 10

您可以使用样式方式在vue 2中使用async组件.正确使用异步组件可以减少项目加载时间.您可以使用async组件:

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')
  }
]
})
Run Code Online (Sandbox Code Playgroud)

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

new Vue ({
  el: 'app',
    components: {
      AsyncComponent: () => import ('./AsyncComponent.vue')
    }
})
Run Code Online (Sandbox Code Playgroud)

您可以访问:www.bdtunnel.com获取更多信息.


Gor*_*rky 5

根据 Vue.js 的文档,从 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: 200 ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000
})
Run Code Online (Sandbox Code Playgroud)

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

提到的文档的更新链接。


dzw*_*lia 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>
Run Code Online (Sandbox Code Playgroud)

基本上,无论何时安装组件,它都会渲染空信息,直到 AJAX 调用完成,然后响应式数据将被更新,Vue 将自动更新响应式数据元素。如果您不想在模板中显示其他标记或内容,则始终可以创建一个inited: false数据属性并将其设置为trueAJAX 回调,然后在包装器上使用:v-if="inited"或指令来隐藏组件的内容,直到AJAX 调用返回。:v-show="inited"div