在Vue 3.2中如何结合defineCustomElement使用Vuex
Vuex Store与defineCustomElement关联使用方案
Vue 3.2 提供的defineCustomElement创建的自定义元素本质仍基于Vue组件实例,和普通Vue应用接入Vuex的逻辑基本一致,核心是在组件实例初始化阶段完成store的注入,常用有两种实现方案:
方案1:自定义元素内部独立集成store
适合自定义元素独立使用、不需要和其他组件共享状态的场景,每个自定义元素实例会持有独立的store状态,互不干扰。
示例代码:import { defineCustomElement } from 'vue' import { createStore, useStore } from 'vuex' // 引入你的自定义元素根组件,带.ce.vue后缀的单文件组件 import MyCustomRoot from './MyCustomRoot.ce.vue' // 创建Vuex store实例 const store = createStore({ state: () => ({ count: 0 }), mutations: { add(state) { state.count++ } } }) // 包装自定义元素 const MyCustomElement = defineCustomElement({ extends: MyCustomRoot, // 注入store插件 plugins: [store], setup() { // 组件内可正常调用store的所有方法 const store = useStore() const handleClick = () => { store.commit('add') console.log(store.state.count) } return { handleClick } } }) // 注册自定义元素,即可在HTML中直接使用<my-custom-element /> customElements.define('my-custom-element', MyCustomElement)方案2:外部传入共享store
适合同页面多个自定义元素需要共享同一份状态的场景,将store实例作为参数传入自定义元素即可。
示例代码:// 自定义元素定义侧 import { defineCustomElement } from 'vue' import { useStore } from 'vuex' const SharedElement = defineCustomElement({ props: { // 定义接收store的props store: { type: Object, required: true } }, setup(props) { // 注册传入的store const store = useStore(props.store) // 后续可正常使用store return {} } }) customElements.define('shared-element', SharedElement)实际使用时传入全局共享的store实例即可:
<shared-element :store="globalVuexStore"></shared-element>
注意:如果你的自定义元素需要在脱离Vue生态的原生HTML环境中使用,优先选择方案1,自定义元素可以完全独立运行,不需要依赖外部提供store实例。
两种方案都可以正常使用Vuex的state、getters、mutations、actions等所有核心能力,不需要额外做兼容处理
内容的提问来源于stack exchange,提问作者Andreas Hunter
相关产品推荐
相关产品推荐

