简体   繁体   中英

Using Pinia with Vue.js Web components

I'm trying to use a Pinia 's store with web components created with Vue.js .
To install Pinia and use it, you're supposed to use 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 . I'm renaming my component in 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. Did you forget to install pinia?
const pinia = createPinia()
app.use(pinia)

It makes sense to me why I get this error, but how can I use Pinia if I can't use app.use(pinia) ?

You're recreating pinia in the store after already creating it in main.js. Remove these lines from your store:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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