Ever wondered why you might need a reactive object compatible with Provide/Inject for your Vuex Store? Well, it's all about flexibility and functionality!
Picture this: you have a plugin for authentication that needs to be integrated into your app. By utilizing a "caveman style" vuex plugin function, you can easily register it within the namespaced User module of your vuex store. The catch? Once registered, the reactivity of the object is lost within the store while Provide/Inject continues to operate seamlessly.
If code speaks louder than words, take a look at the following snippets:
AuthLink.vue
...
export default defineComponent({
setup() {
const auth = inject("Auth") as IAuthPluginProperties;
async function logInFromLink(
withPopUp = false,
options?: {
redirectLoginOptions?: RedirectLoginOptions;
popupConfigOptions?: PopupConfigOptions;
analytics: undefined;
}
): Promise<void> {
if (withPopUp) return auth.loginWithPopup();
//* Add analytics for tracking link-based logins.
return await auth.loginWithRedirect(options?.redirectLoginOptions);
}
function logout(logoutOptions?: LogoutOptions): void {
auth.logout(logoutOptions);
}
return {
auth,
logInFromLink,
logout
};
}
});
</script>
Ready to dive deeper? Let's explore the functionalities in the plugin implementation:
Plugin - index.ts
...
export default {
install: async (app: App, options: pluginInstallOptions): Promise<void> => {
app.config.globalProperties.$auth = Plugin.AuthPluginProperties;
app.provide("Auth", Plugin.AuthPluginProperties);
/*
* Handle defaults from .env vars
*/
if (options.useStore) {
if (!store.hasModule("User")) {
throw new Error("🙈🙉🙊 Looks like something is off... 'User' vuex store module is missing.").stack;
}
await vuexPlugin(store, Vue3AuthPlugin.AuthPluginProperties);
...
Sneak peek into the main.ts file showcasing essential properties:
...
const state = reactive({
isLoading: false,
isAuthenticated: false,
user: undefined,
popupOpen: false,
error: null
}) as IAuthStateProp;
export const AuthPluginProperties = reactive({
isAuthenticated: computed(() => state.isAuthenticated),
isLoading: computed(() => state.isLoading),
user: computed(() => state.user),
// more functions included here
}) as IAuthPluginProperties;
...
Update! Don't miss out on the implementation of the "caveman style" vuex plugin function:
auth-vuex-plugin.ts
import { AuthVuexPlugin } from "../types";
const plugin: AuthVuexPlugin<Record<string, unknown>> = async (store, payload) => {
try {
await store.dispatch("User/INITIALIZE_PLUGIN", payload);
} catch (err) {
throw new Error(`🙈🙉🙊 Oops... Something went wrong with Vuex initialization: ${err}`);
}
};
export default plugin;