Vue -组件外的Pinia使用和存储

rseugnpd  于 2023-08-07  发布在  Vue.js
关注(0)|答案(1)|浏览(205)

我想使用pinia store at test.js文件。在test.js文件我得到了套接字代码。这是我文件结构

/src
 /stores
  mainStore.js
 App.vue
 main.js
 test.js

字符串
mainStore.js

import { defineStore } from 'pinia'

export const useMainStore = defineStore({
    id: 'main',
    state: () => ({
        foo: {},
    }),
    getters: {
        getFoo() {
            return this.foo
        }
    },
    actions: {
        setFoo(foo) {
            this.foo = foo
        }
    }
})


main.js

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

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

app.use(pinia)
app.use(router)

// reload page proof, persist store
if (localStorage.getItem('state')) {
    pinia.state.value = JSON.parse(localStorage.getItem('state'))
}

watch(() => pinia.state, (state) => {
    localStorage.setItem('state', JSON.stringify(state.value))
}, { deep: true })

app.mount('#app')

export { app }


test.js

import { useMainStore } from './stores/mainStore'

const store = useMainStore()


然后我得到了这个错误
enter image description here

Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?
    const pinia = createPinia()
    app.use(pinia)


在互联网上搜索:stores/create_pinia.js

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


test.js

import pinia from './stores/pinia_create'
import { useMainStore } from './stores/mainStore.js'
const store = useMainStore(pinia)


它的工作,但后来我得到了2家商店。快速示例
some_vue_file.vue

<template>
 <div>
  <-- lets assume store.foo is LOREM -->
  {{ store.foo }}.   <-- renders LOREM -->
 </div>
</template>
<script setup>
// import...
// use store...
</script>


test.js

import pinia from './stores/pinia_create'
import { useMainStore } from './stores/mainStore.js'
const store = useMainStore(pinia)
console.log(store.foo)   // writes on console an empty object, {}.

83qze16e

83qze16e1#

main.js

import { createPinia } from 'pinia'

const pinia = createPinia()

const app = createApp(App)

app.use(pinia)

//...

字符串
替换为

import pinia from './stores/pinia_create'

const app = createApp(App)

app.use(pinia)

// move to stores/create_pinia.js
// reload page proof, persist store
//if (localStorage.getItem('state')) {
//    pinia.state.value = JSON.parse(localStorage.getItem('state'))
//}

// ...


stores/create_pinia.js

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

// reload page proof, persist store
if (localStorage.getItem('state')) {
    pinia.state.value = JSON.parse(localStorage.getItem('state'))
}
export default pinia

相关问题