vc-state
A minify local state by using vue composition api.
Usage no npm install needed!
<script type="module">
import vcState from 'https://cdn.skypack.dev/vc-state';
</script>
A minify local state by using vue composition api.
<script type="module">
import vcState from 'https://cdn.skypack.dev/vc-state';
</script>
gt; pnpm add vc-state #or with npm gt; npm install vc-state #or with yarn gt; yarn add vc-state
with CDN
<script src="https://cdn.jsdelivr.net/npm/vc-state/dist/vc-state.min.js"></script>
// @/context.ts
import { createContext } from 'vc-state';
interface AppContext {
count: number;
}
const initialContext: AppContext = {
count: 0,
};
// You can rename by yourself.
const [appContext, useAppContext] = createContext(initialContext);
export { appContext, useAppContext };
// Component.tsx
import { defineComponent, toRefs } from 'vue';
import { useAppContext } from '@/context';
export default defineComponent({
setup() {
const { context: appContext } = useAppContext();
//If want to use a ref value, use `toRefs` to transform context.
//You can watch or watchEffect `count` now.
const { count } = toRefs(appContext);
return () => {
return <div>{appContext.count}</div>;
//return <div>{count.value}</div>
};
},
});
// @/context.ts
import { createContext } from 'vc-state';
import { toRefs } from 'vue';
interface AppContext {
count: number;
}
const initialContext: AppContext = {
count: 0,
};
const [appContext, useAppContext] = createContext(initialContext, (context, setContext) => {
//Define custom actions
function countIncrement() {
context.count++;
}
function setCount(count: number) {
setCount('count', count);
}
//You even can watch context here
const { count } = toRefs(context);
watchEffect(() => {
console.log('count value changed.', count.value);
});
//Will merge into appContext
return { countIncrement, setCount };
});
export { appContext, useAppContext };
// Component.tsx
import { defineComponent, toRefs } from 'vue';
import { useAppContext } from '@/context';
export default defineComponent({
setup() {
const { context: appContext, countIncrement, setCount } = useAppContext();
//If want to use a ref value, use `toRefs` to transform context.
//You can watch or watchEffect `count` now.
const { count } = toRefs(appContext);
watchEffect(() => {
console.log(count.value);
})
return () => {
return (
<>
<div>{appContext.count}</div> {/* Show count */}
<button onClick={countIncrement}><button> {/* Will add 1 to count */}
<button onClick={() => setCount(appContext.count + 10)}><button> {/* Will add 10 to count */}
</>
);
};
},
});
function createContext<S extends Record<string, any>, Selectors extends MutationInit<S>[] = MutationInit<S>[]>(
initialContext: S,
...mutations: Selectors
): [DeepReadonly<State<S>>, () => Context<S, Selectors>];
initialContext
- A initial state in contextmutations
- Any custom hooks in context