只想在点击某些内容时设置一个简单的重定向。不知道如何使用vue-router来做到这一点。请在下面找到我的代码:
app.js
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/' },
{ path: '/product', redirect: '/product' }
]
});
const app = new Vue({
el: '#app'
});
Navbar的main.vue
<template>
<ul class="nav navbar-nav">
<li class="nav-item nav-item-left navbar-btn" @click.prevent="goToHome()" @mouseover.prevent="hoverIcon('home')" @mouseleave.prevent="hoverIcon('')">
<div class="nav-link nav-main" :class="[{ 'navbar-home-hover' : hovered == 'home' },{ 'navbar-home' : hovered !== 'home' }]">Home <span class="sr-only">(current)</span></div>
</li>
<li class="nav-item nav-item-left navbar-btn" @click.prevent="goToProduct()" @mouseover.prevent="hoverIcon('product')" @mouseleave.prevent="hoverIcon('')">
<div class="nav-link nav-main" :class="[{ 'navbar-product-hover' : hovered == 'product' },{ 'navbar-product' : hovered !== 'product' }]">Product</div>
</li>
<li class="nav-item nav-item-left navbar-btn" @mouseover.prevent="hoverIcon('blog')" @mouseleave.prevent="hoverIcon('')">
<div class="nav-link nav-main" :class="[{ 'navbar-blog-hover' : hovered == 'blog' },{ 'navbar-blog' : hovered !== 'blog' }]">Blog</div>
</li>
<li class="nav-item nav-item-left navbar-btn" @mouseover.prevent="hoverIcon('mktInfo')" @mouseleave.prevent="hoverIcon('')">
<div class="nav-link nav-main" :class="[{ 'navbar-mktInfo-hover' : hovered == 'mktInfo' },{ 'navbar-mktInfo' : hovered !== 'mktInfo' }]">Market Info</div>
</li>
</ul>
</template>
<script>
export default {
data(){
return{
hovered: '',
}
},
methods:{
hoverIcon(input){
var vm = this
vm.hovered = input
},
goToHome(){
this.$router.push('/');
},
goToProduct(){
this.$router.push('/product');
}
}
}
</script>
单击Home 时出现错误
未捕获的TypeError:无法读取未定义的属性“push”
编辑#1(在app.js上)
import VueRouter from 'vue-router';
Vue.use(VueRouter); //this is deleted
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/' },
{ path: '/product', redirect: '/product' }
]
});
const app = new Vue({
el: '#app',
router //this is added in this edit
});
答案 0 :(得分:0)
看起来您没有将路由器注入您的应用,因此它未被定义&#39;
要注入路由器,请在 app.js 中的Vue应用中进行以下更改:
const app = new Vue({
el: '#app',
router // inject the router
});
之后,您可以在整个应用中使用this.$router
。
其他方法:
您必须从router
导入app.js
,如下所示:
从&#39; ./ path / to / app
导入路由器之后你可以简单地使用:
router.push