vue3中使用pinia

发布时间 2023-04-26 17:27:29作者: 健生
//npm install pinia

//在mian.ts中引入pinia,然后在createApp中use(pinia)即可
import {createPinia } from 'pinia'
const pinia=createPinia()
createApp(App).use(router).use(pinia).use(Antd).mount('#app')

//在src目录下创建store->index.ts文件

//引入pinia
import { defineStore } from 'pinia'
// useMain  可以是 useUser、useCart 之类的名字 
// defineStore('main',{..}) 在devtools 就使用 main 这个名
export const useMain = defineStore('main', {
    // 相当于data
    state: () => {
        return {
          // 所有这些属性都将自动推断其类型,如果推断失败可以试下 as xxx
          counter: 0,
          name: 'Eduardo',
          list: [1, 2, 3],
        }
    },
    // 相当于计算属性
    getters: {
        doubleCount: (state) => {
            return state.counter * 2
        },
    },
    // 相当于vuex的 mutation + action,可以同时写同步和异步的代码
    actions: {
        increment() {
          this.counter++
        },
        randomizeCounter() {
            setTimeout(() => {
                this.counter = Math.round(100 * Math.random())
            }, 0);
        },
    },
})

//.vue文件中中使用pinia
<template>
    <div>{{ doubleCount }}</div>
    <div>{{name}}</div>
    <div>{{list}}</div>
    <a-button @click="amend()">修改</a-button>
    <a-button @click="user.increment()">修改list的长度</a-button>
    <a-button @click="user.randomizeCounter()">修改list的数据</a-button>
</template>
<script setup lang="ts">
    import {
        UserStore
    } from '../store/user.ts'
    import {
        storeToRefs
    } from 'pinia';
    const user = UserStore()
    const {
        name,
        list,
        doubleCount
    } = storeToRefs(user)
    console.log(name);
    const amend = () => {
        user.$patch((state: {
            name: String,
            list: Array < any >
        }) => {
            state.name = '张三';
            state.list.push('我是新增的数据')
        })
    }
</script>