先創建 router/index.js
import VueRouter from 'vue-router'
import Home from '../components/home/home'
import User from '../components/user/user'
var router = new VueRouter({
routes:[{
name:'test',
path:'/',
meta:{index:0},
component:{
template:'<div>test</div>'
}
},{
name:'home',
path:'/home',
meta:{index:1},
component:Home
},{
name:'user',
path:'/user/:id',
meta:{index:2},
component:User
}]
});
用 watch 監聽 $router 的變化,如果 to.meta.index
大於 from.meta.index
,則是前進狀態
<template>
<div id="app">
<transition :name="transitionName">
<router-view></router-view>
</transition>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
transitionName:''
}
},
watch: {
$route(to, from) {
if(to.meta.index > from.meta.index){
this.transitionName = 'slide-left';
}else{
this.transitionName = 'slide-right';
}
}
}
}
</script>