简体   繁体   English

将 Pinia 与 Vue.js Web 组件一起使用

[英]Using Pinia with Vue.js Web components

I'm trying to use a Pinia 's store with web components created with Vue.js .我正在尝试将Pinia的商店与使用 Vue.js 创建的web组件一起使用。
To install Pinia and use it, you're supposed to use app.use(pinia) :要安装 Pinia 并使用它,您应该使用app.use(pinia)

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')
  1. I'm using Vuejs to create Web component .我正在使用 Vuejs 创建 Web 组件 I'm renaming my component in MyComponent.ce.vue .我正在重命名MyComponent.ce.vue中的组件。

  2. Then I define the custom element:然后我定义自定义元素:

import { defineCustomElement } from 'vue'
import MyComponent from './components/MyComponent.ce.vue'

// convert into custom element constructor
const ExampleElement = defineCustomElement(MyComponent)

// register
customElements.define('my-component', ExampleElement)
  1. I tried to create a store:我试图创建一个商店:
import { createPinia } from 'pinia'
const pinia = createPinia()

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
    state: () => ({ count: 0, name: 'Eduardo' }),
    getters: {
      doubleCount: (state) => state.count * 2,
    },
    actions: {
      increment() {
        this.count++
      },
    },
})

But I get this error:但我得到这个错误:

Uncaught Error: []: getActivePinia was called with no active Pinia.未捕获的错误:[]:调用 getActivePinia 时没有活动的 Pinia。 Did you forget to install pinia?你忘了安装pinia吗?
const pinia = createPinia() const pinia = createPinia()
app.use(pinia) app.use(松果)

It makes sense to me why I get this error, but how can I use Pinia if I can't use app.use(pinia) ?对我来说为什么会出现此错误是有道理的,但是如果我不能使用app.use(pinia) ,我该如何使用 Pinia?

You're recreating pinia in the store after already creating it in main.js.在 main.js 中创建 pinia 后,您将在 store 中重新创建它。 Remove these lines from your store:从您的商店中删除这些行:

import { createPinia } from 'pinia'
const pinia = createPinia()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM