我有嵌套自定義元素的專案。現在我需要 vuex 和 vue 路由器。如何從根自定義元素使用此包,然后在所有子自定義元素中使用?
目前我嘗試只在每個組件中使用 vuex,如下所示:
<script>
import store from './store';
export default {
setup() {
const state = store.state;
return { state };
},
};
</script>
這是帶有嵌套自定義元素的演示專案
這是我的main.js檔案代碼:
import { defineCustomElement } from "./defineCustomElementWithStyles";
import App from "./App.ce.vue";
customElements.define("app-root", defineCustomElement(App));
uj5u.com熱心網友回復:
Vue 插件需要 app 實體,它不是為從defineCustomElement(). 作為一種解決方法,您可以在臨時應用程式實體上安裝插件,然后將生成的背景關系復制到實際應用程式,如該實用程式中所示(我們稍后將使用):
// defineCustomElementWithStyles.js
import { defineCustomElement as VueDefineCustomElement, h, createApp, getCurrentInstance } from 'vue'
export const defineCustomElement = (component, { plugins = [] }) =>
VueDefineCustomElement({
render: () => h(component),
setup() {
const app = createApp()
// install plugins
plugins.forEach(app.use)
const inst = getCurrentInstance()
Object.assign(inst.appContext, app._context)
Object.assign(inst.provides, app._context.provides)
},
})
使用defineCustomElement()上面的而不是來自vue:
// main.js
import { defineCustomElement } from './defineCustomElementWithStyles'
import App from './App.ce.vue'
import store from './store'
import router from './router'
customElements.define(
'app-root',
defineCustomElement(App, {
plugins: [store, router],
})
)
演示
uj5u.com熱心網友回復:
您可以將它們匯入您的main.js檔案中,該檔案是您初始化 vue 實體的檔案。
import Vue from 'vue';
import store from './store';
import { Router } from './router/index.js';
new Vue({
router: Router,
store,
render: h => h(App),
}).$mount('#app');
路線可能與您的不同,因此可以輕松地為您自己的專案編輯它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346186.html
