20

I am converting a VueJS project to Nuxt.js and I have a problem understanding how nuxt handles routing. Its documentation doesn't say anything about Pushing a route.

Using VueJS I have the following in a component.

 //template
 <input class="" type="search"
        name="q" id="q" v-model="q"
        @keyup.enter="submitSearch"
 >
 //script
  methods: {
        submitSearch() {
            this.$route.push({name: 'search', query: {q: this.q}});

            //also tried the following
            //nuxt.$router.push({name: 'search', query: {q: this.q}});

        }
    }

But this doesn't do a thing in Nuxt. Putting an alert('hi); inside the submitSearch fires fine but I am never redirected to the route.

The goal here is when the user presses enter in the searchbar, to be redirected to /search?q=blablabla

EDIT:

The problem is that the user is redirected to /?q=blablabla instead of /search?..

I just realized that this is because there are different names for multilingual routes.

How am I going to push to a route name that instead of 'search' is named search__en dynamically?

mhrabiee
  • 805
  • 10
  • 23

6 Answers6

37

The way I finally did was:

this.$router.push({path: this.localePath('search'), query: {q: this.q}});
kissu
  • 40,416
  • 14
  • 65
  • 133
3

This is how it could be done in Nuxt3, with the Composition API

<script setup>
const router = useRouter()
const moveToIndex = () => router.push({ name: 'about' })
</script>

<template>
  <button @click="moveToIndex">move to about page</button>
</template>

The Options API is still working in the same exact way.

kissu
  • 40,416
  • 14
  • 65
  • 133
2

Faced same problem with Nuxt v2.14.12. After some digging found router object under this.$nuxt.$options.router which is a Nuxt Helper. Currently this.$nuxt.$options.router.push() works fine.

RiadSaidur
  • 147
  • 2
  • 12
1

Not a direct answer but while working with hashing I found this to work well. Will come back to edit this if there are any issues in the future.

this.$router.push(#${hash});

  • 1
    This answer is in the wrong place, but you definitely helped me. Thanks. Also I realized stack overflow converts the backticks you used. – James Ikubi Nov 09 '20 at 11:39
0

For Nuxt3:

const router = useRouter();

router.push({ path: '/home' });
router.push({ path: 'project-list' });
router.replace({ name: 'project-list' });

And list of useful methods:

router.back();
router.forward();
router.go();
Art Mary
  • 562
  • 4
  • 12
0

use NavigateTo

  navigateTo("/reports/" + reportId);
David 天宇 Wong
  • 3,724
  • 4
  • 35
  • 47