背景
需要通过Vue.extend
来挂载实例,并且该实例也需要初始化vuex
,i18n
和vue-router
等。
为了避免代码的重复性,因此扩展了Vue
的构造方法。
主要代码如下:
// BaseVue.js
import Vue from "vue";
import VueI18n from "vue-i18n";
import router from "./router";
import { initStore } from "./store";
import { initStorage } from "./utils/storage";
Vue.use(VueI18n);
export default class BaseVue extends Vue {
constructor() {
super();
}
static async create(component) {
const VueChild = super.extend(component);
const storage = await initStorage();
const store = await initStore(storage);
const i18n = BaseVue.initI18n(store);
await initCacheAndShortcuts(storage);
return new VueChild({
i18n,
store,
router,
storage
});
}
static initI18n(store) {
const i18n = new VueI18n({
locale: store.state.setting.locale,
silentTranslationWarn: true
});
return i18n;
}
}
// main.js
import App from "./App.vue";
BaseVue.create(App).then(App => App.$mount('#app'))
// other.js
import MarketComp from "@/views/web/market/component";
BaseVue.create(MarketComp ).then(MarketComp => MarketComp .$mount('#market'))