使用下一次/上一次单击事件触发 Vue 路由器/组件



我正在使用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 },
]

以下是定义组件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左右(。

最新更新