1、首先需要安装pinia 具体安装和使用教程参考 2、创建 src/stores/counter.js 文件,其内容如下: import {defineStore} from "pinia"; import {ref} from "vue"; export const useCounterStore = defineStore('counter',()=>{ const count = ref(0) const increment = ()=>{ count.value++ } return{ count, increment } }) 3、在.vue中进行验证 <script setup> import {useCounterStore} from "@/stores/counter.js"; import {storeToRefs} from "pinia"; const counterStore = useCounterStore() const {count} = storeToRefs( counterStore) // 注意函数不能用storeToRefs 否则结构出来的不是响应式 const { increment } = counterStore </script> <template> <div> <button @click="counterStore.increment">按钮</button> </div> <h1>{{counterStore.count}}</h1> <div> <button @click="increment">按钮</button> </div> <h1>{{count}}</h1> </template> <style scoped> </style> 实验结果如下: 注意 const {count} = counterStore 这种方式将变量解构出来的count不是响应式的 const {increment } = storeToRefs( counterStore) 同样这种方式将函数解构出来的也不是