3

Vue新一代状态管理插件Pinia

 1 year ago
source link: https://www.fly63.com/article/detial/11554
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-05-23阅读量: 23标签: Pinia分享

扫一扫分享

什么是 Pinia

如果你之前使用过 vuex 进行状态管理的话,那么 pinia 就是一个类似的插件。它是最新一代的轻量级状态管理插件。按照尤雨溪的说法,vuex 将不再接收新的功能,建议将 Pinia 用于新的项目。

Pinia 的优点

  • 简便,存储和组件变得很类似,你可以轻松写出优雅的存储;
  • 类型安全,通过类型推断,可以提供自动完成的功能;
  • vue devtools 支持,可以方便进行调试;
  • Pinia 支持扩展,可以非常方便地通过本地存储,事物等进行扩展;
  • 模块化设计,通过构建多个存储模块,可以让程序自动拆分它们;
  • 非常轻巧,只有大约 1kb 的大小;
  • 服务器端渲染支持。

使用 Pinia 非常简单,你可以通过defineStore来简单创建一个存储管理。

yarn add pinia@next
import {createPinia} from 'pinia'
app.use(createPinia())
import {defineStore} from 'pinia'

export const useTodoStore = defineStore({
    id: "todo",
    state:()=>({count:0,title:"test",done:false})
})
export default defineComponent({
  setup() {
    const todo = useTodoStore()

    return {
      // gives access only to specific state
      state: computed(() => todo.title),
    }
  },
})

同 vuex 的比较

Pinia 最初是为了探索 Vuex 下一次迭代可能会是什么样子,结合了 Vuex 5 核心团队讨论中的许多想法。最终,我们意识到 Pinia 已经实现了我们在 Vuex 5 中想要的大部分内容,并决定实现它取而代之的是新的建议。

628ae927aaea2.jpg
628ae92bf2fda.jpg
628ae930d0f61.jpg
628ae9377afe9.jpg

与 Vuex 相比,Pinia 提供了一个更简单的 api,具有更少的操作,提供了 Composition-API 风格的 API,最重要的是,在与 TypeScript 一起使用时具有可靠的类型推断支持。

如果你正在开发一个新项目,请毫不犹豫地选择 pinia,这不仅仅是当下最好的选择,也将会是未来最好的选择。如果你喜欢 Composition API ,喜欢更简洁的 api 操作,请一定要选择 pinia。

链接: https://www.fly63.com/article/detial/11554


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK