假如有一个需求:
- 多个模块需要使用一个页面
– 但是每个模块里的中央内容都不一样 - 我们可以把页面里的不同内容封装成一个一个组件
– 但如果使用v-if判断显示对应的组件
– 那么假如使用的模块很多 比如30个模块都要使用 那么不得在这个页面里写30个子组件? - 这个方法显然不是最好的 有个好的办法就是通过动态路由去判断当前页面处于什么模块下 就自动渲染对应模块的那个子组件
– 具体代码如下
<template>
<div v-if="flag">
<async-example /> //使用动态路由
</div>
</template>
<script>
import Vue from 'vue';
export default {
created() {
this.initComponent();
},
data() {
return {
flag: false // 判断当前有没有组件 没有组件就不渲染动态路由
};
},
methods: {
initComponent() {
// 从路由的query里拿到对应的文件名拼接路径 文件名从哪里来 看下面的代码
const path = './' + this.$route.query.name;
// 加载这个动态组件 并且根据上面拼接的路径引入对应的子文件
Vue.component('async-example', function (resolve) {
require([`${path}`], resolve);
});
this.flag = true;
}
}
};
</script>
- 每个模块进入页面的时候 都要带一个路由参数
– 参数名字就是你写的组件的名字
this.$router.push('/路由路径?name=文件名');