pinia的vue写法
时间: 2024-11-07 13:13:09 浏览: 43
Pinia是Vue 3官方推荐的状态管理模式,它基于 Vuex 的思想,但去掉了插件系统,采用了更简洁、轻量级的设计。Pinia的核心是一个名为store的工厂函数,用于创建单个状态管理模块。以下是基本的Pinia写法:
1. 安装依赖:
```bash
npm install vue@next pinia @pinia/core
```
2. 创建store:
```javascript
import { createStore } from '@pinia/core';
const myStore = createStore({
id: 'myStore',
state() {
return {
count: 0,
};
},
actions: {
increment() {
this.count++;
},
},
getters: {
doubleCount(state) {
return state.count * 2;
},
},
});
```
3. 注册store到Vue实例上:
```javascript
import { createApp } from 'vue';
import App from './App.vue';
import { useStore } from '@pinia/core/client'; // 引入客户端API
createApp(App)
.use(myStore) // 注册store
.mount('#app');
// 使用store
export default function () {
const store = useStore('myStore');
console.log(store.getters.doubleCount); // 输出当前count的两倍
store.increment(); // 调用increment方法
}
```
阅读全文
相关推荐


















