# Pinia 简介: 功能与`VueX`一样,是个全局状态管理器,尤雨溪推荐 `Vue3` 后使用 `Pinia` 作为全局状态管理器 (~~尤雨溪懂个锤子的`vue`~~) ## 基础使用 ### 引入 Pinia插件 * 新建一个`store/index.js` ```js import { createPinia } from 'pinia' const store = createPinia() export default store ``` * 入口文件导入`./src/main.js` ```js import { createApp } from 'vue' import App from './App.vue' import store from './store/index.cjs' createApp(App).use(store).mount('#app') ``` ### 组件内使用 * 被引入的状态管理 ```js import { defineStore } from 'pinia' /* 写法一: 常规写法 */ export const countStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { }, actions: { setCount (data) { // console.log(arguments) this.count = data } } }) ``` ```js import { defineStore } from 'pinia' import { ref, computed } from 'vue' /* 写法二: 组合式写法 */ export const countStore = defineStore('counter', () => { const count = ref(0) const setCount = (data) => { count.value = data } const getCount = computed(() => count.value) return { getCount, // getters setCount // actions } }) ``` * 其他组件使用 ```js import { countStore } from '../store/counter' // 获取到对应的状态管理 const counter = countStore() // 修改部分状态数据 counter.$patch({ count: 30000 }) // 使用内置方法 counter.addCounter() // 获取属性状态 console.log(counter.count) ``` 最后修改:2023 年 04 月 04 日 © 允许规范转载 赞 0 如果觉得我的文章对你有用,请随意赞赏