kabuto178
kabuto178

Reputation: 3167

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.

Upvotes: 1

Views: 792

Answers (2)

Mahmood Jahan
Mahmood Jahan

Reputation: 1

Because of you are using composition api then you can not use global properties like this.$router or this.$router. With the Composition API, we don't have access to the component instance via this, so Vue Router includes some composables that we can use instead.

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

// confirm user login stuff
// now want to redirect
router.push("/profile");

</script>

For more information you can see Vue 3 documentations here.

Upvotes: 0

ElsaKarami
ElsaKarami

Reputation: 646

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>

Upvotes: 1

Related Questions