Last active
August 27, 2021 05:14
-
-
Save Holi0317/9f74e123ff70afba81fb6f6e75415e8d to your computer and use it in GitHub Desktop.
Dynamic components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<!-- doc: https://vuejs.org/v2/guide/components.html#Dynamic-Components --> | |
<component :is="comp"></component> | |
</template> | |
<script> | |
// Just a fallback component | |
import EmptyComp from "./EmptyComp"; | |
export default { | |
name: "DynamicLoader", | |
data: () => ({ | |
comp: EmptyComp | |
}), | |
methods: { | |
updateComponent(route) { | |
console.log(route); | |
// This is a async component factory | |
// https://vuejs.org/v2/guide/components-dynamic-async.html#Handling-Loading-State | |
this.comp = () => { | |
// Implement your logic here and produce a Future<Component> | |
let component = EmptyComp; | |
if (route.params.comp === "a") { | |
component = import("./ComponentA.vue"); | |
} else if (route.params.comp === "b") { | |
component = import("./ComponentB.vue"); | |
} | |
return { | |
component | |
}; | |
}; | |
} | |
}, | |
created() { | |
this.updateComponent(this.$route); | |
}, | |
// https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes | |
watch: { | |
$route(to) { | |
this.updateComponent(to); | |
} | |
} | |
}; | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from "vue"; | |
import Router from "vue-router"; | |
import DynamicLoader from "./DynamicLoader.vue"; | |
Vue.use(Router); | |
export default new Router({ | |
mode: "history", | |
base: process.env.BASE_URL, | |
routes: [ | |
{ | |
path: "/:comp", | |
name: "home", | |
component: DynamicLoader | |
} | |
] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment