在vue文件外使用store
在外部js或ts使用store时,如果直接引入store使用不会生效有可能还回报下面的错误:
getActivePinia was called with no active Pinia. Did you forget to install pinia
// user.ts
import { defineStore } from 'pinia'
export const userStore = defineStore({
state: {
name: '',
id: '',
}
})
// permission.ts
import { userStore } from '@/store/user'
// 操作没有任何反应或者直接报异常
const user = userStore()
user.name = '123'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
如果要在外部文件中使用store,需要在使用时对store对象传入当期Pinia实例
// stores/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const store = createPinia()
store.use(piniaPluginPersistedstate)
export default store
// user.ts 中添加一下方法
import store from '@/stores'
/* 外部使用store */
export function userStoreOut() {
return userStore(store)
}
// permission.ts
import { userStoreOut } from '@/store/user'
// 这里就可以正常使用或更新
const user = userStore()
user.name = '123'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
原因:在vue文件中会在setup中自动对引入的userStore注入pinia实例,但是在外部文件中需要自行注入。具体请查看官方文档
上次更新: 2025/09/05, 8:09:00