pinia
安装
npm install pinia
初始化哪里一般有 初始化
创建一个 pinia 实例
mian.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia' //这里
import App from './App.vue'
const pinia = createPinia()//这里
const app = createApp(App)
app.use(pinia)//这里
app.mount('#app')
// 这里我一般都是单独写一个文件把import里面写到@store/index.ts然后直接导入文件,例如:
import pinia from '@/store'
app.use(pinia)
@/store/index.ts
import { createPinia } from 'pinia';
// 对外暴露大仓库
export default createPinia();
定义Store
@\store\user\index.ts
import { defineStore } from "pinia";
import { ref } from "vue";
const useUserStore = defineStore("User", () => {
let userInfo = ref("你好");
return { userInfo };
});
// 对外暴露Store
export default useUserStore;
在 Setup Store 中:
- ref() 就是 state 属性
- computed() 就是 getters
- function() 就是 actions
使用 Store
在任意vue文件下面script标签下导入后就可以使用
import { useUserStore } from '@/stores/user'
// 可以在组件中的任意位置访问 `store` 变量
const userStore = useUserStore();