延時加載在vue組件
new Vue({ // ... components: { AsyncCmp: () => import("./AsyncCmp") } });
通過將import
函數包裝到箭頭函數中,Vue將僅在請求時執行它,並在該時刻加載模塊。
延時加載在vue-router
Vue路由器內置支持延遲加載。它就像使用該import
功能導入組件一樣簡單。假設我們想在/ login路由中延遲加載一個Login組件:
// Instead of: import Login from './login' const Login = () => import("./login"); new VueRouter({ routes: [{ path: "/login", component: Login }] });
延時加載在vuex模塊
Vuex有一種registerModule
方法可以讓我們動態創建Vuex模塊。如果我們考慮到該import
函數返回的Promise上來延遲加載模塊:
const store = new Vuex.Store() ... // Assume there is a "login" module we wanna load import('./store/login').then(loginModule => { store.registerModule('login', loginModule) })