如何在重用组件时触发转换?

时间:2016-10-05 11:52:11

标签: vue.js vuejs2 vue-router

如何在同一组件之间转换时触发转换?

(使用vue-router 1,有一个canReuse挂钩。它在vue-router 2中不再存在。)



const Index = {
  template: `<div id="app">
    <router-link :to="{ path: '1' }">page 1</router-link> | 
    <router-link :to="{ path: '2' }">page 2</router-link>
    <router-view></router-view>
  </div>`
};

const Page = {
  template: `<transition @enter="transitionEnter" @leave="transitionLeave">
    <div>
      <p>page {{ id }}</p>
    </div>
  </transition>`,
  data() {
    return {
      id: this.$route.params.id,
    }
  },
  methods: {
    transitionEnter(el, done) {
      console.log('transitionEnter');
      done();
    },
    transitionLeave(el, done) {
      console.log('transitionLeave');
      done();
    },
    fetchData() {
      this.id = this.$route.params.id;
    }
  },
  watch: {
    '$route': 'fetchData'
  },
};

const App = Vue.extend(Index);

const router = new VueRouter({
  routes: [{
    path: '/:id',
    component: Page
  }, {
    path: '*',
    redirect: '/1'
  }]
})

const app = new App({ router }).$mount('#app');
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:6)

使用key上的router-view参数。

const Index = {
  template: `<div id="app">
    <p>app</p>
    <router-link :to="{ path: '1' }">page 1</router-link> | 
    <router-link :to="{ path: '2' }">page 2</router-link>
    <router-view :key="'a' + $route.params.id"></router-view>
  </div>`
};

const Page = {
  template: `<transition @enter="transitionEnter" @leave="transitionLeave">
    <div>
      <p>page {{ id }}</p>
    </div>
  </transition>`,
  data() {
    return {
      id: this.$route.params.id,
    }
  },
  methods: {
    transitionEnter(el, done) {
      console.log('transitionEnter');
      done();
    },
    transitionLeave(el, done) {
      console.log('transitionLeave');
      done();
    },
  },
};

const App = Vue.extend(Index);

const router = new VueRouter({
  routes: [{
    path: '/:id',
    component: Page
  }, {
    path: '*',
    redirect: '/1'
  }]
})

const app = new App({ router }).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app"></div>