Pablo Araújo
Pablo Araújo

Reputation: 83

TypeError: Cannot read property 'push' of undefined using Vue router and Vue 3

Guys I have a problem in Vue 3 and Vite, I'm trying to use the router but I have a problem because they didn't find it.

    props: ["usuario", "senha"],

  setup(props) {
    const mensagemErro = ref("");

    async function login() {
      try {
        const { data } = await services.post("auth/login", {
          userName: props.usuario,
          password: props.senha,
        });
        console.log(data);
        const { token, userName } = data;
        window.localStorage.setItem("token", token);
        this.$router.push("/home");
      } catch (error) {
        console.log(error);
      }
    }

    return {
      login,
      mensagemErro,
    };
  },

Upvotes: 0

Views: 2607

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should use the composable function useRouter to get the instance router :

import {useRouter} from 'vue-router'
export default{
    props: ["usuario", "senha"],

  setup(props) {
    const mensagemErro = ref("");
   const router=userRouter();
   
   async function login() {
      try {
        const { data } = await services.post("auth/login", {
          userName: props.usuario,
          password: props.senha,
        });
        console.log(data);
        const { token, userName } = data;
        window.localStorage.setItem("token", token);
        router.push("/home");
      } catch (error) {
        console.log(error);
      }
    }

    return {
      login,
      mensagemErro,
    };
  },

Upvotes: 2

Related Questions