Kros的博客 Kros的博客
首页
  • CSS
  • 工具
  • Vue
  • js
  • Vue3
  • 算法
  • 折腾笔记
一言
  • 分类
  • 标签
  • 归档
码云

Kros

凡心所向,素履以往,生如逆旅,一苇以航
首页
  • CSS
  • 工具
  • Vue
  • js
  • Vue3
  • 算法
  • 折腾笔记
一言
  • 分类
  • 标签
  • 归档
码云
  • CSS

  • JavaScript

  • 工具

  • Vue

  • antdv踩坑记录

  • Vue3

    • vue3 setup语法糖
    • vue3实现v-model
    • vue3组件通信
    • vue3使用pinia及pinia持久化
    • vue3使用$nextTick
    • Proxy的实际应用场景
    • ref和reactive的实现原理
    • vue3生命周期
    • 在vue文件外使用store
    • vue3中的编译器宏
    • vue3 ts中拼接本地图片地址
    • 数值滚动实现
    • setup语法糖下自定义组件name
    • vue-router4配置动态路由问题No match found for location with path
    • vue3挂载全局弹窗
    • vue3+vite配置环境变量问题
    • Vue3监听createApp创建的子组件事件
    • vue3源码学习——vue3核心模块
  • 前端
  • Vue3
kros
2023-07-03

在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

如果要在外部文件中使用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

原因:在vue文件中会在setup中自动对引入的userStore注入pinia实例,但是在外部文件中需要自行注入。具体请查看官方文档

上次更新: 2025/09/05, 8:09:00
vue3生命周期
vue3中的编译器宏

← vue3生命周期 vue3中的编译器宏→

最近更新
01
Find the next perfect square
09-05
02
Regex validate PIN code
09-05
03
Find the odd int
09-05
更多文章>
Theme by Vdoing | Copyright © 2020-2025 kros king
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
icon-heart-o icon-heart icon-infinity icon-pause icon-play link next prev