1.安装
npm i pinia
2.搭建架子文件
2.1main.js
import { createApp } from 'vue'
// 引入pinia
import { createPinia } from 'pinia'import App from './App.vue'
import router from './router'
// 创建pinia
const app = createApp(App)
//安装pinia
app.use(createPinia())app.use(router)app.mount('#app')
2.2index.js
import {userStore} from "@/stores/modules/user.js";export const useStore=()=>{return {user:userStore()}
}
2.3user.js
import { defineStore } from 'pinia'export const userStore = defineStore('user', {state(){return{sum:6}},actions:{modifySum(param1,param2){console.log(param1,param2)return this.sum++}},getters:{// 想用this就不能用箭头寒素bigSum(state){return this.sum*10}// bigSum:(state)=>state.sum*10}})
3.测试Demo
<script setup>
import {useStore} from "@/stores/index.js"
import {storeToRefs} from "pinia";const countStore = useStore()
// storeToRefs只会关注store里面的数据,而不像toRefs包裹所有的东西。
const {sum} = storeToRefs(countStore.user)// 解构countStore会失去响应式function modify1() {// 修改数据方式1countStore.user.sum = 5
}
// 修改数据2 (有误)
// function modify2(){
// countStore.$dispose({
// user:{
// sum:9
// }
//
// })
// }
// 修改数据3
function modify3() {// 这边写几个参数,对应的actions里面就可以接受几个参数countStore.user.modifySum("启动1", "启动2")
}</script><template><div><div @click="modify3">demo</div>
<!-- 都可以拿到sum的值--><div>pinia里面的值{{countStore.user.sum}}</div><div>pinia里面的值{{countStore.user.$state.sum}}</div><div>pinia里面的值{{ sum }}</div></div>
</template>