我正在尝试将 Nuxt 3 项目作为 Web 组件(聊天机器人 SPA)嵌入到外部网站上。
我在一个使用 Vue 自定义元素的 Vue 3 项目中对此进行了有效的实现,示例代码来自文档:
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
// normal Vue component options here
props: {},
emits: {},
template: `...`,
// defineCustomElement only: CSS to be injected into shadow root
styles: [`/* inlined css */`]
})
// Register the custom element.
// After registration, all `<my-vue-element>` tags
// on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)
// You can also programmatically instantiate the element:
// (can only be done after registration)
document.body.appendChild(
new MyVueElement({
// initial props (optional)
})
)
// vite.config.js
// Bundle app into single js file
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
...
plugins: [cssInjectedByJsPlugin()]
build: {
cssCodeSplit: false,
rollupOptions: {
output: {
entryFileNames: "app.js",
},
},
},
})
然后可以通过包含单个 JS 输出文件和
<my-vue-element></my-vue-element>
元素将该项目嵌入到任何外部网页中。
我无法在 Nuxt 3 中成功重用此逻辑。
任何关于如何使用 Nuxt 3 实现这一目标的见解将不胜感激!
问题解决了吗? 也许这可以帮助你nuxt-custom-elements