Lazy loading a specific component in Vue.js - vue.js

I just make it quick:
In normal loading of a component (for example "Picker" component from emoji-mart-vue package) this syntax should be used:
import {Picker} from "./emoji-mart-vue";
Vue.component("picker", Picker);
And it works just fine.
But when I try to lazy load this component I'm not sure exactly what code to write. Note that the following syntax which is written in the documentation doesn't work in this case as expected:
let Picker = ()=>import("./emoji-mart-vue");

The problem, I'm assuming, is that you're using
let Picker = ()=>import("./emoji-mart-vue");
Vue.component("picker", Picker);
to be clear, you're defining the component directly before the promise is resolved, so the component is assigned a promise, rather than a resolved component.
The solution is not clear and depends on "what are you trying to accomplish"
One possible solution:
import("./emoji-mart-vue")
.then(Picker=> {
Vue.component("picker", Picker);
// other vue stuff
});
This will (block) wait until the component is loaded before loading rest of the application. IMHO, this defeats the purpose of code-spliting, since the application overall load time is likely worse.
Another option
is to load it on the component that needs it.
so you could put this into the .vue sfc that uses it:
export default {
components: {
Picker: () => import("./emoji-mart-vue")
}
};
But this would make it so that all components that use it need to have this added, however, this may have benefits in code-splitting, since it will load only when needed the 1st time, so if user lands on a route that doesn't require it, the load time will be faster.
A witty way to solve it
can be done by using a placeholder component while the other one loads
const Picker= () => ({
component: import("./emoji-mart-vue"),
loading: SomeLoadingComponent
});
Vue.component("picker", Picker);
or if you don't want to load another component (SomeLoadingComponent), you can pass a template like this
const Picker= () => ({
component: import("./emoji-mart-vue"),
loading: {template:`<h1>LOADING</h1>`},
});
Vue.component("picker", Picker);

In PluginPicker.vue you do this:
<template>
<picker />
</template>
<script>
import { Picker } from "./emoji-mart-vue";
export default {
components: { Picker }
}
</script>
And in comp where you like to lazy load do this:
The component will not be loaded until it is required in the DOM, which is as soon as the v-if value changes to true.
<template>
<div>
<plugin-picker v-if="compLoaded" />
</div>
</template>
<script>
const PluginPicker = () => import('./PluginPicker.vue')
export default {
data() = { return { compLoaded: false }}
components: { PluginPicker }
}
// Another syntax
export default {
components: {
PluginPicker: () => import('./PluginPicker.vue')
}
}
</script>

Related

Conditionally import a component in Vue Router

I'd like to conditionnaly import a component in the vue router. Here is what I have for the moment:
children: [
{
path: ':option',
component: () => import('../components/Option1.vue'),
},
],
Depending on what :option is, I want to import a different component (Option1.vue, Option2.vue, etc.). I know I could put several children but i actually need the option variable in my parent component (I make tests if the route has an option).
How would it be possible to do that?
Thanks in advance :)
You can create a loader component containing a dynamic component instead of doing conditional routing. In the loader, you'll conditionally lazy load the option component based on the route param. Not only is this easier when routing, you also don't have to manually import anything, and only options that are used will be imported.
Step 1. Route to the option loader component
router
{
path: ':option',
component: () => import('../components/OptionLoader.vue'),
}
Step 2. In that option loader template, use a dynamic component which will be determined by a computed called optionComponent:
OptionLoader.vue
<template>
<component :is="optionComponent" />
</template>
Step 3. Create a computed that lazy loads the current option
OptionLoader.vue
export default {
computed: {
optionComponent() {
return () => import(`#/components/Option${this.$route.params.option}.vue`);
}
}
}
This will load the component called "Option5.vue", for example, when the option route param is 5. Now you have a lazy loaded option loader and didn't have to manually import each option.
Edit: OP has now indicated that he's using Vue 3.
Vue 3
For Vue 3, change the computed to use defineAsyncComponent:
OptionsLoader.vue
import { defineAsyncComponent } from "vue";
computed: {
optionComponent() {
return defineAsyncComponent(() =>
import(`#/components/Option${this.$route.params.option}.vue`)
);
}
}
Here is something that works in VueJS3:
<template>
<component :is="userComponent"/>
</template>
<script>
import { defineAsyncComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
export default {
computed: {
userComponent() {
const route = useRoute();
const router = useRouter();
const components = {
first: 'Option1',
second: 'Option2',
third: 'OtherOption',
fourth: 'DefaultOption',
};
if (components[route.params.option]) {
return defineAsyncComponent(() => import(`./options/${components[route.params.option]}.vue`));
}
router.push({ path: `/rubrique/${route.params.parent}`, replace: true });
return false;
},
},
};
</script>
Source: https://v3-migration.vuejs.org/breaking-changes/async-components.html
And it's possible to get an error message like this one for the line with "return":
Syntax Error: TypeError: Cannot read property 'range' of null
In that case, it means you probably want to migrate from babel-eslint to #babel/eslint-parser (source: https://babeljs.io/blog/2020/07/13/the-state-of-babel-eslint#the-present)

VUE add a component with JS

Can I create/mount a VUE component calling a JS function in a fullyloaded page?
As a async call? Something like:
function getComponent(obj){
return <component parameters="obj"></component >;
}
Can I create/mount a VUE component calling a JS function in a fullyloaded page?
I think you want to load/mount the component in a certain condition and not on page initialization.
If that the case then you can take advantage of lazy-loading and dynamic components:
<template>
//...
<button #click="activateComponent">Activate component</button>
<component :is="dynamicComponent" />
//...
</template>
<script>
export default {
components: {
MyCmp: () => import('./MyCmp.vue') //lazy loading
},
data: () => ({
dynamicComponent: null
}),
methods: {
activateComponent () {
this.dynamicComponent = 'MyCmp'
}
}
}
</script>
I think what you are looking for is Vue dynamic components. What that allows you is to choose which component to load after the original component has loaded. You can do that whenever and however you want to, aka in an async way. You can read more in the Vue guides. All the code you need is there so won't repost it here again.

Vue dynamic components - watch for mounted

I'm using Webpack dynamic imports and Vue dynamic components to lazy-load a rather large Vue markdown-parsing component.
Now, I want to add syntax highlighting with Prism.js. I'm currently using the mounted() lifecycle hook of the parent component to install syntax highlighting, but this is only working some of the time, since the syntax highlighting depends on the Markdown component to be loaded first (when I manually execute Prism.highlightAll() from the console after page load, it works every time).
Relevant source code:
<template>
<vue-markdown>
# Hello
```javascript
import { hello } from "world"
```
</vue-markdown>
</template>
<script>
export default {
components: {
"vue-markdown": () => import("vue-markdown/src/VueMarkdown"),
},
mounted() {
import("prismjs/themes/prism-tomorrow.css")
.then(() => import("prismjs").then(p => Prism.highlightAll()))
}
}
</script>
So how do I wait for a dynamic component to load? I almost want something like this:
<vue-markdown v-on:mounted="syntaxHighlighting()"></vue-markdown>
I solved the problem by creating my own component which extends the VueMarkdown component, but with a mounted() hook that activates syntax highlighting. It looks like this:
<script>
import VueMarkdown from "vue-markdown/src/VueMarkdown"
import "prismjs/themes/prism-tomorrow.css"
import Prism from "prismjs"
export default {
extends: VueMarkdown,
mounted() {
Prism.highlightAll()
}
}
</script>
Then, I dynamically import this component into the parent component.
Not sure if this is the best solution, though...

vuejs - Async AND Dynamic component

What I want to achive is to combine vuejs's "Async Components" and its "Dynamic Components" (https://v2.vuejs.org/v2/guide/components-dynamic-async.html) to get a flexible way of using dynamic components.
Let's say, I have the following component:
<template>
<div>
some stuff..
<component :is="type"></component>
some stuff...
</div>
</template>
<script>
export default {
name: "mycomponent",
props: {
type: {}
}
}
</script>
I would use it like so:
<mycomponent type="myinput"></mycomponent>
To make it work, I would need to load the myinput component in the mycomponent and I will do it aync:
components: {
MyInput: () => import("./myinput")
}
That works!
The problem now is, that I want to make it dynamic and use it like so:
<mycomponent type="myinput"></mycomponent>
<mycomponent type="myselect"></mycomponent>
<mycomponent type="mytextarea"></mycomponent>
...
To get this up and running, I would need to import all of this components in the mycomponent, which is obviously not an good idea. Global import is as well, not the way to go.
This was just an example, but the real use case for this is getting an array of type's from an api and dynamically render a form with it.
So I have came up with I idea what I could not try yet.
Lets say you have a component for different types of inputs for the sake of simplicity you name them all with an 'Input' prefix.
As long as everyone follows the naming rules you can register all of these component globally.
For example in a BaseInputs.js
const components = require.context(path, subfolder, regexForInputComponentFileNames)
https://webpack.js.org/guides/dependency-management/#require-context
components.keys().forEach(element => {
const componentName = element.replace(/*Everything that is not the component name like .vue*/)
Vue.component(componentName, () => import(path + componentName)
})
Then you just import 'path/to/BaseInputs' at the beginning of your application.

Best Practice for Reacting to Params Changes with Vue Router

When using Vue Router with routes like /foo/:val you have to add a watcher to react for parameter changes. That results in somewhat annoying duplicate code in all views that have parameters in the URL.
This could look like the following example:
export default {
// [...]
created() {
doSomething.call(this);
},
watch: {
'$route' () {
doSomething.call(this);
}
},
}
function doSomething() {
// e.g. request API, assign view properties, ...
}
Is there any other way to overcome that? Can the handlers for created and $route changes be combined? Can the reuse of the component be disabled so that the watcher would not be necessary at all? I am using Vue 2, but this might be interesting for Vue 1, too.
One possible answer that I just found thanks to a GitHub issue is the following.
It is possible to use the key attribute that is also used for v-for to let Vue track changes in the view. For that to work, you have to add the attribute to the router-view element:
<router-view :key="$route.fullPath"></router-view>
After you add this to the view, you do not need to watch the $route anymore. Instead, Vue.js will create a completely new instance of the component and also call the created callback.
However, this is an all-or-nothing solution. It seems to work well on the small application that I am currently developing. But it might have effects on performance in another application. If you really want to disable the reuse of the view for some routes only, you can have a look at setting the key's value based on the route. But I don't really like that approach.
I used this variant without :key prop on router-view component.
routes.js:
{
path: 'url/:levels(.*)',
name: ROUTES.ANY_LEVEL,
props: true,
component: (): PromiseVue => import('./View.vue'),
},
view.vue
<template>
<MyComponent :config="config" />
</template>
---*****----
<script>
data: () => ({ config: {} }),
methods: {
onConfigurationChanged(route) {
const { params } = route
if (params && params.levels) {
this.config = // some logic
} else {
this.config = null
}
},
},
beforeRouteUpdate(to, from, next) {
this.onConfigurationChanged(to)
next()
},
}
</script>
Inside the component, I use the config as a property. In my case, reactivity is preserved and the component is updated automatically from parameter changes inside the same URL.
Works on Vue 2
vue3 and script setup:
watch(route, () => { fetch()})
in import:
import { watch } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()