vuejs loading entire .vue file dynamically from 1 template into another - vue.js

Sorry if this is a repeat - I have had a look around and spent most of today on this issue without getting result I am after.
https://github.com/vahidhedayati/micronaut-vuejs-cqrs/blob/master/frontend/src/components/sample/dynamicForm/PropertySplit.vue#L29
https://github.com/vahidhedayati/micronaut-vuejs-cqrs/blob/master/frontend/src/components/sample/dynamicForm2/Property2.vue#L31
I have two similar vue parent pages that load up dynamic form content, what I am trying to do is to get the actual form content which resides on a totally different .vue file in each of the sub folders above.
If I use Vue.component('form-content' this does work but I end up with 1 instance of the form for both different calls rather than a dynamic form per call. So one of the two forms gets loaded in and reused on both calls.
I have tried to use a const variable instead of Vue.component which works correctly locally on the main vue page that loads in the const variable but I haven't been able to get child page to load up the const value
//import Vue from 'vue'
//Vue.component('form-content', {
// components: { ActualForm },
// template: `<actual-form></actual-form>`
//});
//const content = {
// components: { ActualForm },
// template: `<actual-form></actual-form>`
//}
ActualForm.vue is another page and ideally I want to be able to pass this dyanmically per call on different page to the underlying DynamicForm.vue which will load title etc and then the form as per vue page that is passed in.
It seems trivial not quite sure why I am struggling with this.

You cannot pass a component to another component through a prop. For that you need to use a slot. So your code would look like:
<dynamic-form
:headingText="currentHeadingText"
:sectionHeadingText="currentSectionHeadingText"
>
<actual-form/>
</dynamic-form>
And in the <dynamic-form> component you would write:
<template>
[…]
<slot></slot>
[…]
</template
Then the <actual-form> component would be included at the position of the <slot>-tag. You can also use multiple slots and pass in multiple components / template segments. (Read the docs on vuejs.org for detailed information)
I am not completely sure what you are trying to do though. Maybe you need to structure your application in a different way. E.g. use the <dynamic-form> in the template of the <actual-form>. You could then still pass props to <dynamic-form> and fill slots therein from the <actual-form>.

Related

Nuxt (SSR/Vuex): Dispatch an action once all of the components have been created

Consider the following Widget component.
<template>
<component :is="name" />
</template>
<script>
import { mapActions } from 'vuex';
export default {
props: {
name: {
type: String,
required: true
}
},
created() {
this.addWidget(this.name);
},
methods: {
...mapActions({
addWidget: 'widgets/add'
}) // adds widget name to an array
}
};
</script>
I want to have multiple components like this one all over the page.
I need to be able to gather all of the component names so I can fetch the relevant data for them.
My current idea is to add the component name to the store when the created hook fires.
That works just fine, but my problem is that I can't find a way to dispatch a Vuex action to fetch the data once all of the components have been created. I tried using various hooks to no avail since none of them seems to have Vuex access.
Am I missing something? Is there some kind of hook that fires after all of the components have been created (SSR) that has Vuex access. Or maybe there's some better way to achieve what I've been trying to do?
Why do you want to wait until all the widgets have been loaded to fetch the data? Instead, what I'd do is fetch the data for each Component as they get added in the page. Using this approach, each component would require a specific piece of data, and nothing better than to load each of them in a different request. Easier to test, easier to trace, adheres to the single responsibility principle.
If you are worried that two components may require the same data, then you can route all requests through an Object that hashes the request (endpoint + verb if using REST) and keeps a pool of active connections, so that if two requests come in one reuses the Promise of the other, and only one of them reaches the server.
Now, if you really want to do it using your original approach, make it so that each widget emits an event once it's been registered. The events are collected by the parent component (maybe the Page that loads all the widgets). The page knows which Widgets are being loaded. Every time an event is received it sets a flag on that specific widget to indicate it's been loaded. Once all widgets get a flag, the Page triggers a request to fetch the data.

Vue-Router add new route dynamically when there is a new component

I need to create a fully modular Vue project and I can't figure out how do I add or remove routes when there is a new component or a component is deleted.
Now I statically type all the routes that are available in my Sidebar menu. Let's say there are 10 menus in my sidebar, it means that I should type 10 routes in my routes.js file.
But I need this project to be modular. By saying modular what I mean is, I need to give the component list to the project, I think that I should do that with a .json file and let's say this file says that it has only 5 component available, then the related routes will be dynamically created in the routes.js file, and when one of them is deleted, the related route should be removed from the routes list as well. That is what I want.
I want to do that because I develop a single frontend with Vue for more than one device. These devices may have different options and menus, when the device and the frontend matches, only the available menus will be put in the sidebar, so I can't type all the routes statically as I've been doing the whole time.
Any advice would be appreciated.
You can loop through a list of routes and use the router.addRoute function to dynamically add them to your router instance (requires vue-router 3.5.0+), instead of loading them by default. You could do this from the created() hook of your main layout for example.
// app.vue
<template>
<router-view />
</template>
<script>
export default {
created() {
let routes = loadRoutes(); // insert your own function to get the correct routes here
routes.forEach(route => this.$router.addRoute(route))
},
};
</script>
If you need to be able to switch between different layouts on the same device (like a shared terminal for managers and employees) you can reset the routes array by creating a new router instance, or removeRoute (if you use v4.0+).

How To Ensure Reference Data Is Loaded In Vue?

I have webpack setup to bundle all of the source. I have a Vue object that is the page and multiple Vue components of my own creation. This works great!
I am now getting reference data from the database to fill in certain default options for some of these components. In my pages Mounted or Created events (there is no difference for my question) I am calling a method that will check to see if the data exists in localStorage and if not, it will extract the data from the database.
Once Extracted, I have it in localStorage so it is not an issue. However, the first time I need to gather the data (or when I need to refresh it because I have another trigger that lets me know when it has changed) the page and components have rendered (with errors because of lack of data) before the data comes back. The fetch method is in a promise, but mounted events don't seem to care if a promise exists within in before it continues to the next component.
So what is the best practice for loading/refreshing reference data in Vue? I am currently not using VueX because this is not a SPA. Sure, it is a single page that is doing things (there are many single pages that do their own thing in this site) but I have no need to make it a full SPA here. But If VueX and its store will give me some sort of guarantee that it will occur first or page/components will run AFTER VueX things, I will learn it.
Have you tried doing so:
<component v-if="page.isDataLoaded">...</component>
in your Vue-component:
data() {
return {
page: {
isDataLoaded: false,
}
}
},
mounted() {
this.fetchPageData().then(() => this.page.isDataLoaded = true);
}
You can use v-if and v-else to show, for example page loader element like so:
<PageLoader v-if="!page.isDataLoaded"></PageLoader>
<component v-else>...</component>

Can Vue-Router handle clicks from normal anchors rather than router-link?

I have a scenario where there are two major components on a page; a frame-like component that contains common functionality for many applications (including a bookmark/tab bar) and my actual application code.
Since the frame doesn't actually own the page that it's included on, it seems like it would be incorrect for it to define any routes, however the current page may define their own routes that may match one of those links. In that case, I'd like vue-router to handle those anchor clicks and navigate appropriately rather than doing a full page reload.
Here's a simplified template of what this looks like:
Frame (an external dependency for my app):
<Frame>
<TabStrip>
</TabStrip>
<slot></slot>
<Frame>
App1:
<Frame>
<App>You're looking at: {{ pageId }}!</App>
</Frame>
So when any of the app1 domain links are clicked from that tab strip, I want my route definitions in app1 to pick that up rather than it causing a page load. Since that component is owned by the frame, I don't have access to write <router-link> since links to many different apps may co-exist there.
Any thoughts?
Whoo, this is an old one! However, since this question was high in my search results when I was researching this problem, I figured I should answer it.
My use-case was similar to the one in the comments: I needed to capture normal <a> links within rendered v-html and parse them through the router (the app is rendering Markdown with a light modification that generates internal links in some cases).
Things to note about my solution:
I'm using Vue3, not Vue2; the biggest difference is that this is the new Vue3 composition-style single page component syntax, but it should be easy to backport to Vue2, if necessary, because the actual things it's doing are standard Vue.
I stripped out the markdown logic, because it doesn't have anything to do with this question.
Note the code comment! You will very likely need to design your own conditional logic for how to identify links that need to be routed vs. other links (e.g. if the application in the original question has same-origin links that aren't handled by the Vue app, then copy/pasting my solution as-is won't work).
<script setup>
import { useRouter } from "vue-router"
const router = useRouter()
const props = defineProps({
source: {
type: String,
required: true,
},
})
function handleRouteLink(event) {
const target = event.target
// IMPORTANT! This is where you need to make a decision that's appropriate
// for your application. In my case, all links using the same origin are
// guaranteed to be internal, so I simply use duck-typing for the
// properties I need and compare the origins. Logic is inverted because I
// prefer to exit early rather than nest all logic in a conditional (pure
// style choice; works fine either way, and a non-inverted conditional is
// arguably easier to read).
if (!target.pathname || !target.origin || target.origin != window.location.origin) {
return
}
// We've determined this is a link that should be routed, so cancel
// the event and push it onto the router!
event.preventDefault()
event.stopPropagation()
router.push(target.pathname)
}
</script>
<template>
<div v-html="source" #click="handleRouteLink"></div>
</template>

Preserve component state with vue-router?

I have a listing/detail use case, where the user can double-click an item in a product list, go to the detail screen to edit and then go back to the listing screen when they're done. I've already done this using the dynamic components technique described here: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components. But now that I'm planning to use vue-router elsewhere in the application, I'd like to refactor this to use routing instead. With my dynamic components technique, I used keep-alive to ensure that when the user switched back to the list view, the same selection was present as before the edit. But it seems to me that with routing the product list component would be re-rendered, which is not what I want.
Now, it looks like router-view can be wrapped in keep-alive, which would solve one problem but introduce lots of others, as I only want that route kept alive, not all of them (and at present I'm just using a single top level router-view). Vue 2.1 has clearly done something to address this by introducing include and exclude parameters for router-view. But I don't really want to do this either, as it seems very clunky to have to declare up front in my main page all the routes which should or shouldn't use keep-alive. It would be much neater to declare whether I want keep-alive at the point I'm configuring the route (i.e., in the routes array). So what's my best option?
You can specify the route you want to keep alive , like:
<keep-alive include="home">
<router-view/>
</keep-alive>
In this case, only home route will be kept alive
Vue 3
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
Exactly as is, you don't need a Component attribute in the App.vue. Also your this'll work even if your components don't have a name property specified.
I had a similar problem and looked at Vuex but decided it would require too much changes/additions in my code to add to the project.
I found this library https://www.npmjs.com/package/vue-save-state which solved the problem for me, keeping the state of 1 component synchronized with localStorage, and it only took a few minutes and a few lines of code (all documented in the Github page of the package).
One solution without localStorage:
import {Component, Provide, Vue} from "vue-property-decorator";
#Component
export default class Counter extends Vue {
#Provide() count = 0
/**
* HERE
*/
beforeDestroy() {
Object.getPrototypeOf(this).constructor.STATE = this;
}
/**
* AND HERE
*/
beforeMount() {
const state = Object.getPrototypeOf(this).constructor.STATE;
Object.entries(state || {})
.filter(([k, v]) => /^[^$_]+$/.test(k) && typeof v !== "function")
.forEach(([k]) => this[k] = state[k]);
}
}
What seems to me is you are looking for some kind of state management. If you have data which is shared by multiple components and you want to render component in different order, but dont want to load data again for each component.
This works like following:
Vue offers a simple state management, but I will recommend to use Vuex which is a standard for state management among vue community.