我有一个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$ (....WebUI\src\App.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 (.....\WebUI\src\App.vue:47:1)
EDIT1:
如果我这样做
import router from './router/index';
,然后将路由器称为“路由器”,而不是“ this。$ router”:
export default new Vue({
async mounted() {
...
router.push({ name: 'overview' });
...
},
}).$mount('#app');
有效。
答案 0 :(得分:2)
您需要配置路由器并将其添加到顶级组件。
const router = new VueRouter({
routes: ...
});
export default new Vue({
router, // <-
async mounted() {
...