pinia 配置教程

Pinia.js 是新一代的状态管理器,由 Vue.js团队中成员所开发的,因此也被认为是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的项目中使用也是备受推崇。

Pinia.js 有如下特点:

  • 完整的 typescript 的支持;
  • 足够轻量,压缩后的体积只有1.6kb;
  • 去除 mutations,只有 state,getters,actions(这是我最喜欢的一个特点);
  • actions 支持同步和异步;
  • 没有模块嵌套,只有 store 的概念,store 之间可以自由使用,更好的代码分割;
  • 无需手动添加 store,store 一旦创建便会自动添加;

一、安装

npm install pinia --save //安装pinia
npm install pinia-plugin-persist --save //安装pinia-plugin-persist,数据持久化插件

二、配置

在 src 目录内新建一个 store 的目录,然后在此目录下新建一个 index.ts 文件,内容如下:

import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPluginPersist)

export default store

三、注册pinia

打开项目下的 “main.ts”,在里面追加pinia的内容:

import { createApp } from 'vue'
import App from './App.vue'
// 导入Pinia状态管理器
import store from './store/index'

createApp(App).use(store).mount('#app')

四、创建一个State

在 src/store/modules 目录下新建一个 user.ts 文件,内容如下:

import { defineStore } from 'pinia'

export const userStore = defineStore('userInfo', {
	state: () => {
		return {
			userID: '10001',
			userName: '某同学',
		}
	},
	getters: {
		fullName: (state) => {
			return `${state.userName}(${state.userID})`
		},
	},
	// action 支持 async/await 的语法,可以自行添加使用
	// action 里的方法相互之间调用,直接用 this 访问即可
	actions: {
		updateUserName(name: string) {
			this.userName = name
		},
	},
})


五、使用

<template>
	{{ store.fullName }}
	<p>
		<button @click="onChangeName()">改变Store里的名字</button>
	</p>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userStore } from '@/store/modules/user'

const store = userStore()

const onChangeName = (name) => {
    store.updateUserName(name ?? '李同学')
}

onMounted(() => {
    onChangeName('张同学')
})

</script>

<style scoped></style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值