搜尋

首頁  >  問答  >  主體

使用Vue.js Web元件與Pinia

問題已更新

#

我嘗試使用 Pinia 的商店以及使用 Vue.js 建立的 Web 元件,但控制台中出現此錯誤:

[Vue warn]:在 處找不到注入「Symbol(pinia)」

我有一個非常簡單的例子。

  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>

P粉755863750P粉755863750435 天前570

全部回覆(1)我來回復

  • P粉832212776

    P粉8322127762023-12-21 00:07:25

    在 main.js 中建立 pinia 後,您將在商店中重新建立 pinia。從您的商店中刪除這些行:

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

    回覆
    0
  • 取消回覆