- 安装依赖:
在 Qwik 项目目录下,通过 npm 或 yarn 安装
zustand
。
- 使用 npm:
npm install zustand
- 使用 yarn:
yarn add zustand
- 初始化 Zustand 存储:
在项目合适位置(例如
src/store
目录下)创建 Zustand 存储文件(如 counterStore.ts
)。
import create from 'zustand';
// 创建 Zustand 存储
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 }))
}));
export default useCounterStore;
- 在 Qwik 组件中使用 Zustand 状态:
在 Qwik 组件中引入创建好的 Zustand 存储并使用其状态和方法。
import { component$, useStore } from '@builder.io/qwik';
import useCounterStore from '../store/counterStore';
const CounterComponent = component$(() => {
const { count, increment, decrement } = useStore(useCounterStore);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => increment()}>Increment</button>
<button onClick={() => decrement()}>Decrement</button>
</div>
);
});
export default CounterComponent;