pinia基本使用

129 阅读2分钟

一、 pinia特点

  • 兼容vue2和vue3版本
  • 删除mutations
  • 现不能与vuex 混用
  • 支持插件扩展功能
  • 支持模块热更新无需加载页面可以修改容器,可以保持任何现有的状态
  • 更完美TS支持
  • 支持服务端渲染

二、 基本使用

  • 首先安装
npm install pinia
复制代码
  • 在main.js中引入pinia并创建容器挂载到根实例上
import { createPinia } from 'pinia'
const pinia = createPinia()
// 挂载
createApp(App).use(pinia).mount('#app')
复制代码
  • 创建store/index.js 容器名称 要确保唯一性 将来把所有容器挂载到隔壁容器上 根据唯一的值来获取当前容器 类似于对象的key
import { defineStore } from "pinia" // 定义容器

export const useMain = defineStore('useStore', {
  // 存储全局状态
  // 必须是箭头函数: 为了在服务器端渲染的时候避免交叉请求导致数据状态污染
  state: () => {
    return {
      count: 0,
      list: [1, 2, 3, 4 ]
    }
  },
 //用来封装计算属性 有缓存功能  类似于computed
  getters: {
    
  },
  //编辑业务逻辑  类似于methods
  actions: {

  }

})
复制代码
  • 页面使用
import { useMain } from '../store' // 引入store
const useStoreMain = useMain()
复制代码
<template>
  <div class="greetings">
    <h1 class="green">{{ useStoreMain.count }}</h1>
  </div>
</template>
复制代码
  • 我们可以直接结构出想要的数据,但是数据会出现无法实现响应式问题,官方使用的API reactive 使state数据生成响应式。
  • 引用官方API storeToRef 作用就是把结构的数据使用ref做代理
import { storeToRefs } from 'pinia'
const { count } = storeToRefs(useStore())
复制代码

三、 属性详解

3.1 state

  • 存储全局状态类似于组件中的data
state: () => {
  return {
    count: 0,
    list: [ 1, 2, 3 ]
  }
}
复制代码
  • 对比vuex
const state = () => ({
  count: 0,
  list: [ 1, 2, 3 ]
})
复制代码

3.2 getter

  • 封装计算属性 有缓存功能 类似于computed 对比与vuex,pinia中的getters只是在幕后做计算,不能传递任何参数,但是可以使用getter返回一个函数接受任何参数
getters: {
  getNum(state) {
    return state.count + 1
    // return  this.count + 1
  }
}
复制代码
  • 这里需要传入state才能拿到数据,可以直接使用state和this效果是一样的
  • 和计算属性一样的是你可以写很多getter通过this来直接访问依据官网文档
getters: {
    doubleCount: (state) => state.counter * 2,
    doubleCountPlusOne() {
      return this.doubleCount + 1
    }
  }
复制代码
  • 页面使用
<p>{{ useStoreMain.getNum }}</p>
复制代码
  • vuex中使用getters
<p>{{ store.getters.getNum }}</p>
复制代码

3.3 actions

actions: {
  addList() {
    this.count ++
  }
}
复制代码
  • 在这里我们获取state里数据是不需要传入直接使用this,actions 方法可以互相调用直接使用this
  • 如果我们批量更改数据建议使用$patch方法,这样我们可以优化性能
useStoreMain.$patch({
  	count: useStoreMain.count += 1
})
// $patch 支持函数
useStoreMain.$patch(state => {
	// state 就是容器
})
// actions 更改多个数据 也建议使用$patch
复制代码

对比于VueX

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})