Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: this.$route.push is not a function vue.js and Uncaught TypeError: Cannot read property 'push' of undefined

i am getting an error like "TypeError: this.$route.push is not a function" even i tried ES6 also to bind this, still not working. whenever I click a button which is "Get Homepage Data" in about.vue it should redirect to home page. is working but here i need to call ajax and after ajax response only it has to redirect,,, so that i am not using

router.js

import Vue from "vue";
import Router from "vue-router";
import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage from "../components/FallBackPage/FallBackPage.vue";
import MyOrders from "../components/MyOrders/MyOrders.vue";

 Vue.use(Router);

export function createRouter() {
  return new Router({
  mode: "history",
  routes: [
   { path: "/", component: Home },
   { path: "/about", component: About },
   { path: "/myorders", component: MyOrders },
   { path: "/*", component: FallBackPage }
  ]
 });
}

main.js

 import Vue from "vue";
 import App from "./App.vue";
 import { createRouter } from "./router/router.js";

  export function createApp() {

   const router = createRouter();

   const app = new Vue({
      router,
      render: h => h(App)
  });

 return { app, router };
 }

about.vue

 <template>
  <div>
    {{ aboutText }}
     <button  @click="gobackToHome">Get Homepage Data</button>
  </div>
</template>
<script>
export default {
   data() {
    return {
      aboutText: "About Component"
    };
  },
  method: {
     gobackToHome: function() {

        this.$route.push("/")

   // $route or $router both are not working


    }

    // gobackToHome: () => {
      //  this.$route.push("/")
     // }

   }

};
</script>
like image 403
D V Yogesh Avatar asked Nov 16 '18 14:11

D V Yogesh


1 Answers

I think the issue is you aren't importing vue-router into your app. Only into router.js and then you don't import all of router.js into your app, only the createRouter function. Try this:

//routes.js

import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage from "../components/FallBackPage/FallBackPage.vue";
import MyOrders from "../components/MyOrders/MyOrders.vue";

export const routes [
   { path: "/", component: Home },
   { path: "/about", component: About },
   { path: "/myorders", component: MyOrders },
   { path: "/*", component: FallBackPage }
  ]




//main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import {routes} from './routes'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes
})

new Vue({
      router,
      render: h => h(App)
  }).$mount('#app')

Then in your component you use this.$router.push("/")

like image 126
Andrew1325 Avatar answered Oct 08 '22 00:10

Andrew1325