Pinia的使用

1. Pinia 是什么?

Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3

		相比vuex去掉了mutations,操作数据更简单灵活方便

2. Pinia 优势

简单易于学习
轻量化, 仅有 1 KB
模块化设计,便于拆分状态

3. 安装 Pinia

使用 npm
npm install pinia
使用 yarn
yarn add pinia

4. 使用

1.在main.js中注册并使用

import { createApp } from 'vue'
// 导入 pinia
import { createPinia } from 'pinia'
import App from './App.vue'
// 然后注册使用
createApp(App).use(createPinia()).mount('#app')

2.在src目录下创建store文件夹,然后创建store.js文件

import { defineStore } from "pinia";

export const useStore = defineStore({
	id: 'user', // 必须指明唯一的pinia仓库的id
	state: () => ({
        name: '小明',
        address: '上海',
        age: 18,
        hobby: ['唱', '跳', 'rap']
    }),
    actions: {
    	// actions 中可通过 this 来获取state中的数据
    	// val 调用时时传过来的数据
    	updateName(val) {
            this.name = this.name + val 
        },
        syncUpdateHobby(val) {
        	setTimeout(() => {
				this.hobby.push(val)
			})
        }
    },
    getters: {
		getName(state) {
			// 方式1
			// return state.name
			// 方式2
			return this.name
		}
	}
})
  1. 在组件中使用pinia的数据可以直接使用 . 的方式来使用
<template>
    <h1>展示Pinia store</h1>
    <h2>我是: {{store.name}}</h2>
    <h2>getters获取的名字: {{store.getName}}</h2>
    <h2>地址: {{store.address}}</h2>
    <h2>年龄: {{store.age}}</h2>
    <h2>爱好: {{store.hobby}}</h2>
    <button @click="store.name += 'O(∩_∩)O哈哈~'">直接修改名字</button>
    <button @click="editName">actions修改名字</button>
    <button @click="syncHobby">actions异步添加爱好</button>
    <button @click="editStore">同时修改多个store</button>
</template>
    
<script>
import { useStore } from '../store/user'

export default {
    setup () {
        let store = useStore()
        console.log(store);
        function editName() {
			store.updateName('嘿嘿嘿')
		}
        function syncHobby () {
            store.syncUpdateHobby('giao,giao,gaio!!!')
        }
        function editStore () {
            store.$patch({
                name: store.name += '哈哈哈',
                address: store.address += '上海~'
            })
        }
        return {
            store,
            editName,
            syncHobby,
           	editStore,
        }
    }
}
    
</script>
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值