0.2.3 • Published 3 years ago

vue-context-composition v0.2.3

Weekly downloads
2
License
MIT
Repository
github
Last release
3 years ago

vue-context-composition makes sharing your composed state a breeze! It's the missing useContext hook from React, reimplemented for Vue.js 3.0.

Installation

npm install --save vue-context-composition

Or with Yarn:

yarn add vue-context-composition

Usage

defineContext

Define a context that can be provided and used in the component hierarchy. Pass in a create function that will be run as part of setup(). All Vue reactive methods such as computed may be used.

export const userNameCtx = defineContext(() => {
  const userName = ref("");
  const uppercaseUserName = computed(() => userName.value.toUpperCase());
  const setUserName = (name) => {
    userName.value = name;
  };
  return {
    userName: readonly(userName),
    uppercaseUserName,
    setUserName,
  };
});

provideContext

Provide context from a component in the hierarchy. All descendant components can then use that context.

import { userName } from "@contexts/user";

export default defineComponent({
  setup() {
    provideContext(userName);
  },
});

createContext

Shorthand function to create a context that can be provided to all components in the application setup.

import { userName } from "@contexts/user";

createApp(App)
  .provide(...createContext(userName))
  .mount("#app");

useContext

Use context provided in an ancestor component or in application setup.

import { userName } from "@contexts/user";

export default defineComponent({
  setup() {
    const { uppercaseUserName, setUserName } = useContext(userName);
    return {
      uppercaseUserName,
      setUserName,
    };
  },
});

Example project

See the example Vue3 project folder for a project with several examples.

0.2.3

3 years ago

0.2.2

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago