我收到类似“TypeError: this.$route.push is not a function”的错误,即使我也尝试使用 ES6 绑定(bind)它,但仍然无法正常工作。每当我单击 about.vue 中的“获取主页数据”按钮时,它都应该重定向到主页。正在工作,但在这里我需要调用 ajax 并且在 ajax 响应之后它只需要重定向,这样我就不会使用
路由器.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 }
]
});
}
主要.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 };
}
关于.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>
最佳答案
我认为问题在于您没有将 vue-router 导入到您的应用程序中。仅导入 router.js 然后您不会将所有 router.js 导入您的应用程序,仅导入 createRouter 函数。试试这个:
//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')
然后在您的组件中使用 this.$router.push("/")
关于vue.js - TypeError : this. $route.push 不是函数 vue.js 和 Uncaught TypeError: Cannot read property 'push' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53340049/