Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...