Skip to content

Instantly share code, notes, and snippets.

@Acry
Last active November 8, 2020 19:19
Show Gist options
  • Save Acry/a860d96a11931c1c466d38878ef87f9e to your computer and use it in GitHub Desktop.
Save Acry/a860d96a11931c1c466d38878ef87f9e to your computer and use it in GitHub Desktop.

Composition (Composable functions)

Using pug & vuetify here.

In the past vuex was the solution to share state.

In react there are hooks.

create a new file use-login.ts

copy the logic:

const isLoggedIn = ref(false);

const logIn = () => {
  isLoggedIn.value = true;
};

wrap in into:

import { ref } from '@vue/composition-api';
export default function useLogin () {
 // logic goes here
 return {
   // what needs to be used
 };
}
// use-login.ts
import { ref } from '@vue/composition-api';

export default function useLogin(): { isLoggedIn; logIn } {
  const isLoggedIn = ref(false);
  const logIn = (): void => {
    isLoggedIn.value = true;
  };
  return { isLoggedIn, logIn };
}

to consume now use:

<template lang="pug">
  v-container
    h3 Vue Testing
    .div {{isLoggedIn ? 'Hello User' : 'Please login' }}
    .v-btn(v-if='!isLoggedIn' @click='logIn()') log in
</template>

<script lang="ts">
import useLogIn from './use-login';
export default {
  setup() {
    const { logIn, isLoggedIn } = useLogIn();
    return {
      isLoggedIn,
      logIn,
    };
  },
};
</script>

State Management

To share the state of the isLoggedIn variable change the code to:

import { ref } from '@vue/composition-api';
import Vue from 'vue'
import { VueCompositionApi } from '@vue/composition-api';

Vue.use(VueCompositionApi);

const isLoggedIn = ref(false);

export default function useLogin(): { isLoggedIn; logIn } {

  const logIn = (): void => {
    isLoggedIn.value = true;
  };
  return { isLoggedIn, logIn };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment