尝试在 VueJS 中使用路由器时"Type Error: Cannot read property 'push' of undefined"



我看过每一个类似的问题,但似乎没有答案可以解决我的问题。

当我的路由器挂载时,我在尝试在 VueJS 组件中使用 router.push 时收到此错误,因此应该可以通过这个.$router 访问。

我正在使用 vue-cli。

如何修复此错误?

这是我的代码:

主.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router';
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')

路由器代码:

import Vue from 'vue';
import VueRouter from 'vue-router';
//Pages
import Home from '@/pages/home/Index.vue';
import Contact from '@/pages/contact/Index.vue';
import Article from '@/pages/article/Index.vue';
Vue.use(VueRouter);
//Route list
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/contact',
name: 'contact',
component: Contact,
},
{
path: '/article/:id',
name: 'article',
component: Article,
}
];
const router = new VueRouter({
routes,
mode: 'history'
});
export default router;

App.vue:

<template>
<div id="app">
<Home/>
</div>
</template>
<script>
import Home from "@/pages/home/Index.vue"
export default {
name: 'app',
components: {
Home
}
}
</script>
<style>
html, body, #app {
width: 100%;
height: 100%;
}
body {
margin: 0;
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
#app a {
color: #E7E6E6;
text-decoration: none;
}
#app a:hover {
color: rgb(160, 160, 160);
}
</style>

Thumbnail.vue,我试图在其中调用路由器的组件:

<template>
<a href="" @click="redirectToArticle">
<div class="thumbnail">
<img class="image" :src="require(`../../../assets/${imgName}`)"/>
<div class ="overlay">
<div class = "container-titre">
<p v-html="title"></p>
</div>
</div>
</div>
</a>
</template>
<script>
export default {
name: "Thumbnail",
props:
{
imgName: String,
title: String,
articleId: String
},
methods:
{
redirectToArticle(e)
{
//This is the line that generates the error
this.$router.push({name: "article", params:{ id: this.$props.articleId } });
e.preventDefault();
}
}
};
</script>
<style scoped>
.thumbnail {
position:relative;
width: 250px;
height: 250px;
margin:75px;
}
.thumbnail:hover .overlay
{
opacity: 0.8;
}
.overlay
{
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: .5s ease;
background-color: lightgray;
left:0;
top:0;
font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
text-align: center;
}
.container-titre
{
position:relative;
width: 100%;
background-color:darkslateblue;
height: 30px;
top: 197px;
font-size: 24px;
color:#E7E6E6;
}
.image
{
width: 250px;
height: 250px;
}
</style>

似乎问题来自我安装 vue-cli。我做了一个新项目,把同样的代码放进去,它工作了,即使我的原始项目有所有的节点模块,包括vue-router。

确保检查是否有相同的问题。

相关内容

最新更新