2017-10-06 394 views
1

我正在使用Advanced-Async-Components加載async component加載後的應用程序。所以,我曾嘗試下面的代碼:Vue異步組件加載沒有延遲,無論'延遲'參數

Index.vue

<template> 
    <div class=""> 
     <Async></Async> 
    </div> 
</template> 

<script> 
    // async component 
    import LoadComp from '@/components/Loading' 
    import ErrorComp from '@/components/Error' 
    const Async =() => ({ 
     // The component to load. Should be a Promise 
     component: import('@/components/Async'), 
     // A component to use while the async component is loading 
     loading: Load, 
     // A component to use if the load fails 
     error: ErrorComp, 
     // Delay before showing the loading component. Default: 200ms. 
     delay: 4000, // <--- this is not effecting the loading of component 
     // The error component will be displayed if a timeout is 
     // provided and exceeded. Default: Infinity. 
     timeout: 3000 
    }) 

export default { 
    components: { 
     Async 
    } 
} 
</script> 

Async.vue

<template lang="html"> 
    <div class=""> 
     Lorem ipsum dolor sit amet, con .... very larger string/data 
    </div> 
</template> 

<script> 
export default { 
} 
</script> 

<style lang="css"> 
</style> 

上面的代碼工作正常,但它沒有delay參數的影響( Index.vue)。根據官方文檔delay延遲顯示加載組件之前。它應該在4000ms之後加載組件,但它會立即加載。

這是怎麼發生的?

除了使用setTimeout之外,還有其他方法可以實現嗎?

附加信息

我以前webpack模板生成使用vue-cli

Vue version : ^2.4.2 

回答

1

出現這種情況的項目,因爲delay選項顯示裝載組件之前,以毫秒爲單位的延遲量,它是通過loading選項指定的組件,用於顯示異步組件正在加載(此文檔措辭不佳)。

在下面的示例中,兩秒鐘後加載兩個異步組件。第一個沒有延遲,其加載組件(LoadingComponent)將立即顯示。第二個是delay500,這意味着半秒鐘後,它將顯示其加載組件。

const LoadingComponent = { template: `<h1>Loading...</h1>` } 
 
const NumberBoxComponent = { template: `<h1>123123</h1>` } 
 

 
const AsyncComponent1 =() => ({ 
 
    component: new Promise((resolve) => { 
 
    setTimeout(() => { 
 
     resolve(NumberBoxComponent) 
 
    }, 1000) 
 
    }), 
 
    loading: LoadingComponent, 
 
}) 
 

 
const AsyncComponent2 =() => ({ 
 
    component: new Promise((resolve) => { 
 
    setTimeout(() => { 
 
     resolve(NumberBoxComponent) 
 
    }, 1000) 
 
    }), 
 
    loading: LoadingComponent, 
 
    delay: 500 
 
}) 
 

 
new Vue({ 
 
    el: '#app', 
 
    components: { 
 
    'async-component1': AsyncComponent1, 
 
    'async-component2': AsyncComponent2 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script> 
 
<div id="app"> 
 
    <async-component1></async-component1> 
 
    <async-component2></async-component2> 
 
</div>

如果你想拖延異步組件的實際負荷,你應該使用setTimeout

+0

感謝哥們,雖然我已經嘗試過'setTimeout',只是想嘗試更好的方法。但現在這只是我想的方式。只有一個問題,在延遲時間後觸發setTimeout?如果上面代碼中的'setTimeout'與'delay'相比要少很多,那麼該怎麼辦呢? –

+1

上面例子中的setTimeout函數是在延遲被指定後觸發的。如果組件的加載時間少於延遲量,則加載組件將不會顯示。 – thanksd