我正在使用vue-cli路由器。我有单独的组件。在下一个/上一个点击事件中,从一个页面切换到另一个页面的最佳方法是什么?谢谢!
// App.vue
<nav>
<router-link to="/">Homepage</router-link>
<router-link to="/link_1">About</router-link>
<router-link to="/link_2">Portfolio</router-link>
<router-link to="/link_3">Contact</router-link>
</nav>
<div @click="next">Go to next link</div>
<div @click="preview">Go to previous link</div>
// router/index.js
const routes = [
{ path: '/', component: home },
{ path: '/link_1', component: About },
{ path: '/link_2', component: Portfolio },
{ path: '/link_3', component: Contact },
]
答案 0 :(得分:0)
以下是如何定义App
组件
export default {
name: 'app',
data () {
return {
routes: [],
currentRouteId: 0
}
},
mounted () {
this.routes = this.$router.options.routes
// Init currentRouteId from URL
this.refreshCurrentRouteId(this.$router.currentRoute.fullPath)
// Handle manual page change
this.$router.afterEach((to, from) => { this.refreshCurrentRouteId(to.path) })
},
methods: {
refreshCurrentRouteId (currentPath) {
this.currentRouteId = this.routes.findIndex(route => route.path === currentPath)
},
next () {
console.log('Going to next page')
this.currentRouteId++
if (this.routes.length === this.currentRouteId) {
// Go back to first route
this.currentRouteId = 0
}
this.$router.push(this.routes[this.currentRouteId])
},
preview () {
console.log('Going to previous page')
this.currentRouteId--
if (this.currentRouteId === -1) {
// Go to last route
this.currentRouteId += this.routes.length
}
this.$router.push(this.routes[this.currentRouteId])
}
}
}
它将导航router/index.js
文件中定义的路线并处理手动导航(使用router-link
左右)。