Search code examples
vue.jsvue-routervuejs3vue-composition-apivue-router4

Vuejs 3 Router Cannot read property 'push' of undefined


I am currently trying to start a Vue app which will contain a user login. For some reason the I have been struggling with getting this router redirect to work.

The implementation is straight from the vueschool page and specifically aimed at the composition API.

What am I missing here?

Every time I run the registration script it registers the user correctly and logs the error that it can't find the 'push' property on of undefined. My code completion is telling me it's there, the linting works fine and the IDE Webstorm isn't giving any errors.

<script>
import firebase from "firebase/app";
import "firebase/auth";
import { defineComponent, ref } from "vue";
import { useRouter } from "vue-router";

export default defineComponent({
  name: "Register",
  setup() {
    const form = ref({
      email: "",
      password: "",
      error: "",
    });

const pressed = () => {
  const user = firebase
    .auth()
    .createUserWithEmailAndPassword(form.value.email, form.value.password);

  user
    .then((user) => {
      console.log(user);
      const router = useRouter();
      router.push("/about");
    })
    .catch((e) => console.log(e.message));
};

    return {
      form,
      pressed,
    };
  },
});
</script>

Hope it is just something simpel


Solution

  • const router = useRouter(); must be declared in the scope of the setup hook not inside any inner scope :

    setup(){
    
       const router = useRouter();
    
        const form = ref({
          email: "",
          password: "",
          error: "",
        });
    
    const pressed = () => {
      const user = firebase
        .auth()
        .createUserWithEmailAndPassword(form.value.email, form.value.password);
    
      user
        .then((user) => {
          console.log(user);
         
          router.push("/about");
        })
        .catch((e) => console.log(e.message));
    };
    
        return {
          form,
          pressed,
        };
      },