2016-09-18 82 views
3

我有一個相當沉重的組件,我想異步加載,同時在加載時向用戶顯示加載微調組件。顯示異步Vue 2組件的加載微調器

這是我第一次嘗試,使用data中定義的loading連接到與微調組件v-if="loading"。不幸的是,這並不工作,因爲它似乎Vue公司不會重新綁定this正確的函數中components -

export default { 
    data: { 
    return { 
     loading: false, 
    }; 
    }, 

    components: { 
    // ... 
    ExampleComponent: (resolve) => { 
     // Doesn't work - 'this' is undefined here 
     this.loading = true; 
     require(['./ExampleComponent'], (component) => { 
     this.loading = false; 
     resolve(component); 
     }); 
    }, 
    }, 
}; 

我也發現了一些Vue公司1.0的例子,但他們依靠$refs - 2.0 $refs沒有反應時間更長,不能用於此目的。剩下的唯一方法是讓子組件本身在其掛載生命週期事件上對應用程序數據狀態執行一些操作,以刪除加載微調器,但這似乎有點沉重。有一個更好的方法嗎?

回答

1

您可以在對象範圍外聲明一個變量(但仍在模塊範圍內),然後使用created鉤子附加this。因此,您的更新代碼將如下所示:

let vm = {} 

export default { 
    // add this hook 
    created() { 
    vm = this; 
    }, 

    data: { 
    return { 
     loading: false, 
    }; 
    }, 

    components: { 
    // ... 
    ExampleComponent: (resolve) => { 
     // since 'this' doesn't work, we reference outside 'vm' 
     vm.loading = true; 
     require(['./ExampleComponent'], (component) => { 
     vm.loading = false; 
     resolve(component); 
     }); 
    }, 
    }, 
};