为什么会这样$App.vue中未定义路由器



我有一个Vue.js应用程序,它有多个组件,其中一些组件使用路由器的方式如下:

this.$router.push({
name: 'overview',
params: { ... },
});

但是如果我尝试在App.vue中做同样的操作:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
import store from './store/index';
Vue.use(Vuetify);
Vue.use(VueRouter);
require('./components/vue-flash-message/FlashMessage.css');
export default new Vue({
async mounted() {
...
this.$router.push({ name: 'overview' });
...
},
}).$mount('#app');

我得到"无法读取未定义"的属性"push"。可以在这里访问吗?

调用堆栈是

TypeError: Cannot read property 'push' of undefined
App.vue:49
at Vue._callee2$ (....WebUIsrcApp.vue:49:1)
at tryCatch (http://localhost:8080/app.js:5728:40)
at Generator.invoke [as _invoke] (http://localhost:8080/app.js:5962:22)
at Generator.prototype.(anonymous function) [as next] (http://localhost:8080/app.js:5780:21)
at step (http://localhost:8080/app.js:5458:30)
at http://localhost:8080/app.js:5476:14
at new Promise (<anonymous>)
at new F (http://localhost:8080/app.js:7082:28)
at http://localhost:8080/app.js:5455:12
at Vue.mounted (.....WebUIsrcApp.vue:47:1)

第1版:

如果我做这个

import router from './router/index';

然后将路由器称为"router",而不是"this"$路由器’:

export default new Vue({
async mounted() {
...
router.push({ name: 'overview' });
...
},
}).$mount('#app');

它是有效的。

您需要配置一个路由器并将其添加到顶级组件中。

const router = new VueRouter({
routes: ...
});

export default new Vue({
router, // <-
async mounted() {
...

最新更新