Search code examples
vue.jsvue-routervuejs3

Redirecting users after an action


I am trying to achieve having a redirection if the user logs in successfully. I was trying to call this.$router.push('/profile') with then the call back after login however I get an error stating Error Cannot read properties of undefined (reading '$router') I am not sure if there is a new flow to how to get this done since I am using composition with <script setup> syntax. I read the document reference online but still not seeing anything concrete as to how to do this type of navigation now. How can I achieve this with the new vue3 composition api? It seems I am missing something.


Solution

  • If you use setup() inside the script, you can't access the router with $router. if you use vue3, this code can help you:

    <script>
    import { defineComponen } from 'vue'
    import { useRouter } from 'vue-router'
    
    export default defineComponent({
      setup() {
        const router = useRouter()
        function login() {
         router.push('/profile')
        }
        return {
          login
        }
      }
    })
    </script>