Javascript 使用下一个/上一个单击事件触发Vue路由器/组件
我使用的是vue cli,路由器。我有独立的组件。在下一次/上一次点击事件中,从一个页面切换到另一个页面的最佳方式是什么?谢谢大家!Javascript 使用下一个/上一个单击事件触发Vue路由器/组件,javascript,vue.js,Javascript,Vue.js,我使用的是vue cli,路由器。我有独立的组件。在下一次/上一次点击事件中,从一个页面切换到另一个页面的最佳方式是什么?谢谢大家! // App.vue <nav> <router-link to="/">Homepage</router-link> <router-link to="/link_1">About</router-link> <router-link to="/li
// 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.vue
主页
关于
文件夹
接触
转到下一链接
转到上一链接
//路由器/index.js
常数路由=[
{path:'/',组件:home},
{path:'/link_1',component:About},
{path:'/link_2',component:Portfolio},
{path:'/link_3',组件:Contact},
]
以下是如何定义应用程序组件的方法
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])
}
}
}
它将通过
路由器/index.js
文件中定义的路由进行导航,并处理手动导航(使用路由器链接
左右)。谢谢,这个。$router.go(1)和这个。$router.go(-1)完成这项工作!你确定这就是你想要的吗?它使用浏览器历史记录从您访问的页面转到历史记录中的下一个/上一个页面单击“下一步”时,您不想从主页转到“关于”页面吗?这不是我想要的:(现在我尝试了,我想这只是历史记录的后退/前进)。