vue3+ts插件之pinia使用(个人笔记)

191 阅读1分钟

1.npm install pinia -S

2.main.ts引入挂载

import { createPinia } from "pinia" //替换vuex的更好的 舒服的方便的
const store = createPinia()
let app = createApp(App)
app.use(store)
app.mount('#app')

3.src新建store文件夹和ts文件

image.png

4.store.ts内容

import { defineStore } from "pinia"
// 更好的vuex状态管理插件
export const useStore = defineStore('info', {
    state: () => ({
        name: '阿毛子',
    }),
    // computed 获取值
    getters: {

    },
    // method 做修改操作 支持同步异步
    actions: {
         async changNameAction(name: string) { //参数是调用的地方传入的值
            this.name = name
        },
    }
})

5.app.vue调用

import { useStore } from "./store/store";
const store = useStore();
const username = computed(() => store.name);
setTimeout(() => {
  store.changNameAction("张三");
}, 2000);
console.log(store);

6.效果图

image.png