在 svelte 中区分存储变量和正态变量的最佳命名约定是什么?

What is best naming convention to distinguish between store and normal variable in svelte?

提问人:Eddie Jeong 提问时间:9/15/2023 最后编辑:H.B.Eddie Jeong 更新时间:9/15/2023 访问量:43

问:

我目前正在努力以纤细的方式命名商店(可写、可读等)。

商店.ts

export type CanvasContext = ReturnType<typeof createCanvasStore>

export const createCanvasStore = () => {
  const canvasState = writable<CanvasState>('idle')

  // other writable stores...

  return {
    canvasState,
    // other writable stores...
  }
}

const canvasContextSymbol = Symbol('canvasContext')

export const useCanvasContext = () => useContext(canvasContextSymbol, createCanvasContext)

逻辑.ts

export const changeCanvasState = (payload: {canvasState: CanvasState, canvasStateStore: Writable<CanvasState>}) => {
  
  const { canvasState, canvasStateStore } = payload

  if (canvasState === 'idle') {
    canvasStateStore.set('pressed')
  } else {
    canvasStateStore.set('idle')
  }
}

App.svelte

<script lang='ts'>
  import { useCanvasContext } from './store'
  import { changeCanvasState } from './logic'

  const canvasContext = useCanvasContext()

  const {
    canvasState,
    // many other writables...
  } = canvasContext

  const handleClick = () => {
    changeCanvasState({
      canvasState: $canvasState,
      canvasStateStore: canvasState,

      // ...canvasContext
      // I want pass canvasContext but name colliding
    })
  }
<script/>

<div>
  {$canvasState}
</div>
<button on:click={handleClick}>
  change canvas state
</button>

我正在使用这个命名约定,我想用logic.ts无缝地做到这一点,而不是通过传递canvasContext来解构useCanvasContext。

有什么想法吗?

svelte 服务器端渲染 命名约定 sveltekit 可写

评论

0赞 brunnerh 9/15/2023
我不明白你为什么首先传递内容和商店。路过商店应该就足够了。
0赞 Eddie Jeong 10/10/2023
是的,我接受你的建议。即使我必须使用'get()'从存储函数中获取值。唯一的缺点是性能略有下降。谢谢👍🏻

答: 暂无答案