Appearance
Vue2.6 集成
Vue2.6 项目不能直接渲染 Vue3 组件。Lingxi UI 提供 SDK,把 Vue3 组件挂载到 Vue2 页面中的 DOM 容器里。
核心模型
| 方法 | 作用 |
|---|---|
mountAiChat(options) | 挂载内置聊天面板 AiChatPanel |
mountLingxiComponent(Component, options) | 挂载任意导出的 Lingxi UI 组件 |
instance.update(props) | Vue2 数据变化后同步给 Vue3 组件 |
instance.call(methodName, ...args) | 调用 Vue3 组件 defineExpose 暴露的方法 |
instance.unmount() | 页面销毁时卸载 Vue3 应用 |
生命周期注意事项
Vue2 SDK 的本质是在 Vue2 页面里的 DOM 容器上创建一个独立 Vue3 app。业务页面需要显式管理它的生命周期。
| 阶段 | 必须动作 | 原因 |
|---|---|---|
mounted | 创建 SDK 实例并 mount 到稳定 DOM 容器 | Vue3 组件需要真实 DOM 才能初始化。 |
| Vue2 data 更新后 | 调用 instance.update(nextProps) | Vue2 data 不会自动同步到独立 Vue3 app。 |
| 调用组件方法 | 调用 instance.callMethod(name, ...args) | 只可调用 Vue3 组件通过 defineExpose 暴露的方法。 |
beforeDestroy | 调用 instance.unmount() | 清理 Vue3 app、事件监听、异步任务和 DOM。 |
事件统一通过 props 传入。普通事件使用 onSend、onAction、onError 这类 onXxx 命名;update:modelValue 使用字符串 key:'onUpdate:modelValue'。
可视化示例
Vue2 Options API 示例
html
<template>
<div ref="chatContainer"></div>
</template>
<script>
import { mountAiChat } from '@zhiyongui/lingxi-ui/sdk'
import '@zhiyongui/lingxi-ui/style.css'
export default {
data() {
return {
instance: null,
loading: false,
messages: [
{ id: 1, role: 'assistant', content: 'Lingxi UI mounted in Vue2.6.' }
]
}
},
mounted() {
this.instance = mountAiChat({
container: this.$refs.chatContainer,
props: {
messages: this.messages,
loading: this.loading,
onSend: this.handleSend
}
})
},
beforeDestroy() {
this.instance && this.instance.unmount()
},
methods: {
handleSend(content) {
this.messages = this.messages.concat({ id: Date.now(), role: 'user', content })
this.instance.update({ messages: this.messages })
},
setDraft() {
this.instance.callMethod('setDraft', 'Text from Vue2')
}
}
}
</script>受控组件示例
js
this.instance = mountLingxiComponent(AiRichContent, {
container: this.$refs.richContent,
props: {
modelValue: this.document,
editable: true,
'onUpdate:modelValue': (nextDocument) => {
this.document = nextDocument
},
onAction: (action, block) => {
console.log(action, block.id)
},
},
})
// Vue2 侧主动切换只读状态
this.instance.update({ readonly: true })
// 调用 Vue3 expose
this.instance.callMethod('applyDelta', {
type: 'block_delta',
id: 'answer',
content: '追加内容',
})常见问题
页面切换后控制台还有事件或请求怎么办?
检查 beforeDestroy 是否调用了 instance.unmount()。同一个 DOM 容器重复 mount 前也应先 unmount 旧实例。
Vue2 修改数组后 Vue3 组件没有变化怎么办?
修改 Vue2 data 后调用 instance.update({ propName: nextValue })。建议传入新的数组或对象引用,避免原地修改后难以追踪。
为什么事件没有触发?
确认事件是以 props 传入,而不是 Vue2 模板事件。比如 send 对应 onSend,update:modelValue 对应 'onUpdate:modelValue'。