pinia 的使用(笔记)

1. Pinia 与 Vuex 的区别

  • Pinia 是 Vue 的状态管理库,相当于 Vuex 取消了 mutations,取消了 Module 模块化命名空间
  • 现在的 pinia 采用的是扁平化,每一块 store 都是一个命名空间
  • 还支持了 plugins 等

2. pinia 安装与搭建

  • 使用 npm 安装
    npm i pinia
    
  • 创建 store/index.js 文件
    import { defineStore } from "pinia"
    
    // defineStore(当前 store 的 Id, {配置项})
    export const useCountStore = defineStore("count", {
      // 状态
      state: () => {
        return {
          count: 1
        }
      },
      // 计算属性
      getters: {
        // 这里的计算属性使用时,为一个属性而不是方法
        increaseNum(store) {
          return store.count * 10
        }
      },
      // 方法
      actions: {
        addCount(value) {
          this.count += value
        }
      }
    })
    
  • main.js 中引入
    // 这是 Vue3 的引入方式,Vue2 不太一样
    import { createApp } from "vue";
    import App from "./App.vue";
    import { createPinia } from "pinia";
    
    const app = createApp(App);
    app.use(createPinia());
    app.mount("#app");
    

这样就可以在任意位置引入 store 了

3. pinia 的使用

3.1 基本使用
<script setup>
import { useCountStore } from "../store/index.js";

// 可以直接通过 store. 去获取 state、getters、actions 中的属性和方法了
const countStore = useCountStore();
// 直接获取
countStore.count // 1

// 计算属性获取
countStore.increaseNum // 10

// 修改状态1
countStore.count += 1

// 修改状态2
countStore.addCount(1)

// 修改状态3,这种方式和 React 中的 setState 很像
countStore.$patch({
  count: countStore.count + 1
})

// 修改状态4
countStore.$patch((state) => {
  state.count += 1
})

// 替换状态(不是覆盖状态),需要新的状态去替换旧的,如果 key 值不相同就是添加新状态
countStore.$state = {count: 2}

// 重置状态
countStore.$reset()

// 这个时候在使用其他组件引入 countStore 时,count 也是为最新的
</script>
3.2 订阅状态
<script setup>
import { useCountStore } from "../store/index.js";

const countStore = useCountStore();

// store 中的值,每修改一次就会触发
countStore.$subscribe(({ events, storeId, type }, state) => {
  // 里面包含了一些信息
  events
   
  // 这个 store 的 Id,这里是 count
  storeId

  /*
	修改值的方式:
	  'direct':直接修改、使用 action 中的方式修改
	  'patch object':使用 $patch({}) 修改
	  'patch function':使用 $patch((state)=>{}) 修改、使用 $state 替换、$reset()重置
  */
  type
});
</script>
3.3 订阅 actions
<script setup>
import { useCountStore } from "../store/index.js";

const countStore= useCountStore();

// action 中的函数每次调用,都会触发一次
countStore.$onAction(({ args, name, store, after, onError }) => {
  // 调用 actions 中函数的传参列表
  args

  // 函数名称
  name

  // store 对象
  store

  // 当函数正常执行完成后执行
  // result 接收函数返回成功状态的 Promise
  after((result) => {
    console.log(result);
  });

  // 当函数中存在失败状态的 Promise,或函数抛出异常时执行
  onError((err) => {
    console.log(err);
  });
});

</script>

4. 定义 Store

4.1 Option Store
// 这里相当于 vue2 的选项式 API
export const useCountStore = defineStore('count', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})
4.2 Setup Store
// 这里相当于 vue3 的组合式 API
export const useCountStore = defineStore('count', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3 Pinia是一个基于Vue3的状态管理库,它提供了类似于Vuex的全局状态管理能力,同时使用起来更加简单方便。下面是Vue3 Pinia的使用步骤: 1. 安装Vue3 Pinia 你可以使用npm或者yarn安装Vue3 Pinia: ``` npm install pinia ``` 或者 ``` yarn add pinia ``` 2. 创建Pinia Store 你需要创建一个store来管理你的状态。一个store就是一个拥有状态和操作状态的对象。下面是一个例子: ``` import { defineStore } from 'pinia' export const useCounterStore = defineStore({ id: 'counter', state: () => ({ count: 0 }), actions: { increment() { this.count++ } } }) ``` 这个例子中,我们创建了一个名为useCounterStore的store,它拥有一个状态count,初始值为0,并且有一个操作increment,用来增加count的值。 3. 在Vue组件中使用Store 你可以在Vue组件中使用createPinia函数创建一个Pinia实例,并通过inject注入到组件中。然后就可以通过store来获取状态和操作状态了。下面是一个例子: ``` <template> <div> <p>{{ count }}</p> <button @click="increment">+1</button> </div> </template> <script> import { defineComponent, inject } from 'vue' import { useCounterStore } from './store' export default defineComponent({ setup() { const store = useCounterStore() const count = computed(() => store.count) const increment = () => { store.increment() } return { count, increment } } }) </script> ``` 这个例子中,我们通过useCounterStore函数来获取useCounterStore实例,并且通过computed函数来获取count的值。然后我们在increment函数中调用store的increment方法。 4. 相关问题: 1. Vue3 Pinia与Vuex有什么区别? 2. 如何在多个组件之间共享状态? 3. Vue3 Pinia如何处理异步操作? 4. Vue3 Pinia如何处理模块化?

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值