Vue3+Pinia开发Todo应用遇getActivePinia错误求助
解决Pinia报错“getActivePinia() was called but there was no active Pinia”及页面空白问题
你的问题出在App.vue的script顶层直接调用了useTodosStore(),此时Vue实例还未完成Pinia的挂载,Pinia没有激活的实例,因此触发报错,进而导致组件渲染失败,页面空白。
错误原因分析
在Options API的script顶层代码会在组件实例创建前执行,这时候app.use(pinia)的挂载逻辑还没走完,Pinia还没有和当前组件实例关联,调用useTodosStore()自然找不到Active Pinia。
两种修复方案
方案1:使用Options API的生命周期钩子(created)
把获取store的逻辑放到组件的created钩子中,此时组件实例已创建,Pinia也已挂载完成:
<template> <main> <input /> <button>Add</button> <div v-for="todo in todos" :key="todo.id"> <strong>{{ todo.text }}</strong> <button>Toggle</button> </div> </main> </template> <script> import { useTodosStore } from '@/store/todos'; export default { name: 'App', data() { return { todos: [] }; }, created() { const todosStore = useTodosStore(); this.todos = todosStore.todos; } }; </script>
方案2:改用Vue3推荐的<script setup>语法
<script setup>的代码会在组件的setup阶段执行,此时Pinia已经完成挂载,直接调用store即可:
<template> <main> <input /> <button>Add</button> <div v-for="todo in todosStore.todos" :key="todo.id"> <strong>{{ todo.text }}</strong> <button>Toggle</button> </div> </main> </template> <script setup> import { useTodosStore } from '@/store/todos'; const todosStore = useTodosStore(); </script>
补充说明
如果后续需要修改store中的数据,建议直接操作store实例(比如todosStore.todos.push(...)),而不是把store的state赋值到组件的data中,这样能保证数据响应式的一致性。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

