typescript - Pinia 存储与可组合函数

标签 typescript vue.js pinia

我想弄清楚使用 Pinia 存储而不是仅使用纯 ts 可组合函数的优势是什么

const userName = ref('')

export default function useUser() {

  const setUserName(name: string) => {
    userName.value = name
  }

  return {
    userName: readonly(userName),
    setUserName
  }

}

然后是用法


const {userName, setUserName} = useUser()

因为例如这里的 Vitesse 示例 https://github.com/antfu/vitesse/blob/main/src/store/user.ts Pinia 的用法看起来非常相似

感谢澄清:)

最佳答案

我找到了这个解释,它对我来说很有意义:

I feel like you may be missing the point of Composables and the Composition API a bit - they are useful as a way of organising your code "feature-first", rather than "component-first" (literally, throught composition). This means that Composables are shared functionality, not state.

Certain functionalities may include internal (shared, app-wide) state, but that isn't the purpose of Composables per se. Pinia, on the other hand, is meant for sharing state exclusively. It may include functionality to manage said state, but it doesn't exist without that shared state.

A good place to see this "in action" is Vue Use, a set of common-use composables. Some may include internal state, but most do not, so that only augment a component's functionality, perhaps adding some local state (as opposed to global, shared state)

来源:https://www.reddit.com/r/vuejs/comments/t88xzy/comment/hzmoet2/?utm_source=share&utm_medium=web2x&context=3

关于typescript - Pinia 存储与可组合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72606278/

相关文章:

laravel - 使用 vue js 和 laravel 添加表数据时获取未定义的值

javascript - 如何从 Vue Pinia 商店中的操作导航到另一条路线?

javascript - 如何使用 fetch polyfill、rollup 和 typescript 创建 umd 包?

reactjs - 如何在 React 中附加到无状态组件的引用?

typescript - 高级 TypeScript 参数约束

vue.js - VueJS : Pinia direct changes to state and $patch() which one is more performant or is better to use

javascript - 在 pinia 商店中的状态更改后,vue 组件不会更新

c# - typescript 编译器可以生成 POCO .NET 类型/程序集吗?

javascript - v-绑定(bind) :style with array of styles

vue.js - 视觉 : What is the cleanest way to select a component via CSS?