How to redirect another router in Vue3 ? (used next.router in Laravel 8 with vue3)

Viewed 1437

It does not redirect after successfully logged in. getting a console error TypeError: Cannot read property 'push' of undefine Here my code.

I'm creating SPA in vue3 with Laravel 8.

    import { ref } from "vue";
    import { useRoute } from "vue-router";
    export default {
        setup() {
            const form = ref(
                {
                    email: "hudson.vilma@example.net",
                    password: "password",
                    isLoading: false,
                },
            );
            const user = ref("");

            function login() {
                axios.get('/sanctum/csrf-cookie').then(response => {
                    axios.post('/login', this.form).then(response => {
                        this.$router.push('/dashboard')
                       // useRoute.push('/dashboard');  
                      //  this.$router.push({ name: "Dashboard" });
                    }).catch(error => console.log(error)); // credentials didn't match
                });
            }
            
            return { form, login, user , useRoute};
        },
    };
</script>

in app.js instant of vue &

require('./bootstrap');

import { createApp } from "vue";
import App from "./view/App.vue";

import router from "./router";

const app = createApp(App);
app.use(router);
app.mount("#app");
2 Answers

Try to use useRouter instead of useRoute and instantiate it like const router =useRouter() in setup function:

    import { ref } from "vue";
    import { useRouter } from "vue-router";
    export default {
        setup() {
          const router =useRouter()
            const form = ref(
                {
                    email: "hudson.vilma@example.net",
                    password: "password",
                    isLoading: false,
                },
            );
            const user = ref("");

            function login() {
                axios.get('/sanctum/csrf-cookie').then(response => {
                    axios.post('/login', this.form).then(response => {
                        router.push('/dashboard')
                    
                    }).catch(error => console.log(error)); // credentials didn't match
                });
            }
            
            return { form, login, user ,};
        },
    };
</script>

Note that this couldn't be used in composition API.

You are using this.$router.push('/dashboard') in setup(). This cannot be used in setup(). Instead you can use...

router.push('/dashboard')
Related