|
| 1 | +import Vue from 'vue' |
| 2 | +import VueRouter from 'vue-router' |
| 3 | + |
| 4 | +Vue.use(VueRouter) |
| 5 | + |
| 6 | +const store = Vue.observable({ |
| 7 | + replace: false, |
| 8 | + time: new Date().getTime() |
| 9 | +}) |
| 10 | + |
| 11 | +const computed = { |
| 12 | + replace () { |
| 13 | + return store.replace |
| 14 | + }, |
| 15 | + time () { |
| 16 | + return store.time |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const Home = { computed, template: '<div>home {{replace}} {{time}}</div>' } |
| 21 | +const Page = { computed, template: '<div>page {{replace}} {{time}}</div>' } |
| 22 | +const Detail = { computed, template: '<div>detail {{replace}} {{time}}</div>' } |
| 23 | + |
| 24 | +const router = new VueRouter({ |
| 25 | + mode: 'history', |
| 26 | + base: __dirname, |
| 27 | + routes: [ |
| 28 | + { path: '/', component: Home }, |
| 29 | + |
| 30 | + { path: '/page', component: Page }, |
| 31 | + |
| 32 | + { path: '/detail', component: Detail } |
| 33 | + |
| 34 | + ] |
| 35 | +}) |
| 36 | + |
| 37 | +// User can check the replace type in navigation guard, and do anything they want. |
| 38 | +router.beforeEach((to, from, next) => { |
| 39 | + store.replace = to.replace |
| 40 | + store.time = new Date().getTime() |
| 41 | + next() |
| 42 | +}) |
| 43 | + |
| 44 | +new Vue({ |
| 45 | + router, |
| 46 | + template: ` |
| 47 | + <div id="app"> |
| 48 | + <h1>Push Or Replace</h1> |
| 49 | + <p>User can check the replace type in navigation guard, and do anything they want.</p> |
| 50 | + <pre> |
| 51 | +router.beforeEach((to, from, next) => { |
| 52 | + if (to.replace) { |
| 53 | + to.query.replace = true |
| 54 | + } |
| 55 | + else { |
| 56 | + to.query.replace = false |
| 57 | + } |
| 58 | + if (to && to.query && !to.query.time) { |
| 59 | + to.query.time = new Date().getTime() |
| 60 | + next(to) |
| 61 | + } else { |
| 62 | + next() |
| 63 | + } |
| 64 | +}) |
| 65 | + </pre> |
| 66 | + <ul> |
| 67 | + <li><router-link to="/">/</router-link></li> |
| 68 | + <li><router-link to="/page">/page</router-link> ( push )</li> |
| 69 | + <li><a @click="$router.push('/page')">/page</a> $router.push('/page') </li> |
| 70 | + <li><router-link to="/detail" replace>/detail</router-link> ( replace )</li> |
| 71 | + <li><a @click="$router.replace('/detail')">/detail</a> $router.replace('/detail') </li> |
| 72 | + <li><a @click="$router.go(-1)">back</a> $router.go(-1) </li> |
| 73 | + </ul> |
| 74 | + <router-view class="view"></router-view> |
| 75 | + </div> |
| 76 | + ` |
| 77 | +}).$mount('#app') |
0 commit comments