Fully dynamic vue-router

。_饼干妹妹 提交于 2019-11-29 15:41:16

It's possible to do. I have created a codepen for you to test:

Here it is:

Vue.use(VueRouter);

let A = {
  mounted() {
    console.log('Mouted component A');
  },
};
let B = {
  mounted() {
    console.log('Mouted component B');
  },
};
let C = {
  mounted() {
    console.log('Mouted component C');
  },
};

const router = new VueRouter({
  mode: "hash",
  routes: [
    {
      path: '*',
      beforeEnter(to, from, next) {
        let components = {
          default: [A, B, C][Math.floor(Math.random() * 100) % 3],
        };
        to.matched[0].components = components;
        
        next();
      }
    },
  ]
});

app = new Vue({
  router,
  el: '#app',
  components: { A, B, C }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <router-link :to="'/' + Math.random()">anything</router-link>
  <router-view></router-view>
</div>

This is the output:

As you can see in the console logs - each time something changes we get random component loaded and mounted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!