pinia原创
全局状态管理。
参考 vuex4 (opens new window)
vue3以后将转向Pinia
,所以新项目最好用Pinia
。
# install
npm install -S pinia
yarn add -D pinia
# setting
- 在
src
目录下建立文件夹store
。 - 在
store
文件夹下建立文件index.js
。// xxx.ts or xxx.js import {defineStore} form "vuex"; // 命名规范请使用 use export const useXxxxStore = defineStore('唯一的id',{ // 必须是箭头函数 返回一个对象 , 存储状态 state:{}, // getter 类似 computed 修饰一些值,可以对 state 的数据进行运算 getters:{}, // action 类似 methods 可以做同步、异步,提交state actions:{} }) export default store;
- 在项目的
main.js
中添加相关store
代码:import { createApp } from 'vue' import store from './store' import App from './App.vue' creatApp(App) .use(store) .mount('#app')
# use
在*.vue
中使用
<template>
// 从 store 中获取 xxx 的数据
{{xxx}}
</template>
<script setup>
...
import {mapState} from 'vuex'
...
export default {
...
computed:{
...mapState(['xxx'])
// 即从 ./store/index.js 中拿到 states 中的 xxx 的数据
}
...
}
</script>
# 创建 store
// xxxStore.js
import { defineStore } from 'pinia'
export const xxxStore = defineStore('xxx', {
state: () => {
return {
xxx: 'xxx'
}
}
})
# 使用
<script setup lang="ts">
import { mainStore } from '@/stores/MainStore'
mainStore()
</script>
上次更新: 2022/08/23, 18:12:45