我查看了每个类似的问题,但似乎没有答案可以解决我的问题。
当我的路由器已安装时,我尝试在 VueJS 组件中使用 router.push 时遇到此错误,因此应该可以通过 this.$router 进行访问。
我正在使用 vue-cli。
如何修复此错误?
这是我的代码:
main.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;
应用程序.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 在内的所有节点模块。
请务必检查您是否遇到相同类型的问题。
关于javascript - "Type Error: Cannot read property ' 尝试在 VueJS 中使用路由器时推送 ' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60032159/