Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

vuejs3 - Correct way of reusing functions in Composition API

I use Vue3 Composition API and am trying to explore its reusability possibilities. But I feel that I don't understand how it should be used.

For example, I extracted the login function to a file, to use it on login, and also after registration.

@/services/authorization:

import { useRoute, useRouter } from "vue-router";
import { useStore } from "@/store";
import { notify } from "@/services/notify";

const router = useRouter(); // undefined
const route = useRoute(); // undefined
const store = useStore(); // good, but there is no provide/inject here.

export async function login(credentials: Credentials) {
  store
    .dispatch("login", credentials)
    .then(_result => {
      const redirectUrl =
        (route.query.redirect as string | undefined) || "users";
      router.push(redirectUrl);
    })
    .catch(error => {
      console.error(error);
      notify.error(error.response.data.message);
    });
}

interface Credentials {
  email: string;
  password: string;
}

@/views/Login:

import { defineComponent, reactive } from "vue";
import { useI18n } from "@/i18n";
import { login } from "@/services/authorization";

export default defineComponent({
  setup() {
    const i18n = useI18n();

    const credentials = reactive({
      email: null,
      password: null
    });

    return { credentials, login, i18n };
  }
});

And the problem is that route and router are both undefined, because they use provide/inject, which can be called only during setup() method. I understand why this is happening, but I don't get what is correct way to do this.

Currently, I use this workaround @/services/authorization:

let router;
let route;

export function init() {
  if (!router) router = useRouter();
  if (!route) route = useRoute();
}

And in Login (and also Register) component's setup() i call init(). But I feel that it's not how it's supposed to work.

question from:https://stackoverflow.com/questions/65648007/correct-way-of-reusing-functions-in-composition-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...