我想使用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, {}.
型
1条答案
按热度按时间83qze16e1#
main.js
字符串
替换为
型
stores/create_pinia.js
型