Using Pinia with Vue.js Web components

Viewed 171

Question has been updated

I'm trying to use a Pinia's store with web components created with Vue.js but I have this error in the console:

[Vue warn]: injection "Symbol(pinia)" not found at <HelloWorld.ce msg="message" >

I have a dead simple exemple.

  1. main.ts
import { defineCustomElement } from 'vue'
import HelloWorld from './components/HelloWorld.ce.vue'

const ExampleElement = defineCustomElement(HelloWorld)
customElements.define('hello-world', ExampleElement)
  1. store.ts
import { defineStore, createPinia, setActivePinia } from "pinia";

setActivePinia(createPinia());

export const useCounterStore = defineStore('counter', {
  state: () => ({
    counter: 0,
  }),

  actions: {
    increment() {
      this.counter++;
    },
  },
});
  1. HelloWorld.ce.vue
<script setup lang="ts">
import { ref } from 'vue'
import { useCounterStore } from '../store.ts'

defineProps<{ msg: string }>()

const store = useCounterStore()
</script>

<template>
  <h1>{{ msg }}</h1>
  <div class="card">
    <button type="button" @click="store.increment()">count is {{ store.counter }}</button>
  </div>
</template>
1 Answers

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()
Related