Vue Pinia切换函数仅生效一次无法回切问题求助
问题排查与解决
你的问题核心出在组件中对toggleBox的定义上:
const toggleBox = computed(() => { return store.toggleFunktion() })
错误原因
computed是计算属性,用于根据现有状态衍生新值,它会在组件初始化时自动执行一次,这直接触发了toggleFunktion(),把eineVariable从true改成了false。- 点击事件
@click="toggleBox"实际上绑定的是这个计算属性的返回值(toggleFunktion()没有返回值,即undefined),后续点击时根本没有调用toggleFunktion(),所以状态无法继续切换。
修复方案
把toggleBox直接改为对store中action的引用,不需要用computed:
import {useStore} from "../store/index.js" import {computed} from 'vue' // Vue3需导入computed const store = useStore() const isActive = computed(() => { return store.getEineVariable }) // 直接引用action,无需包裹computed const toggleBox = store.toggleFunktion
或者更简化,直接在点击事件中调用action,不用额外定义变量:
<div class="piniaBox" :class="{ 'active': isActive}" @click="store.toggleFunktion"></div>
可选优化
你的gettergetEineVariable只是直接返回state值,其实可以省略getter,直接使用state变量:
const isActive = computed(() => { return store.eineVariable })
修改后点击div就能正常反复切换状态了。
内容的提问来源于stack exchange,提问作者mikasa
相关产品推荐
相关产品推荐

