VueJS Process complete template before operations - vuejs2

Good afternoon.
I have an interesting problem at the moment. We have a third party server that offer translations for static html content. I need to fetch this content via Ajax and display it in my Vue components.
The current situation
These translations are fetched via a dictionary-like data structure, i.e. via a category and a key. We have incorporated a Vue plugin to load these into our components via a function t, like this:
<template>
<section>
<h1>{{ t('CommonHeaders', 'HomePage') }}</h1>
<p v-html="t('Articles', 'SiteDescription')"></p>
</section>
</template>
At the moment these translations are shipped to the browser by embedding them in the HTML, after which our client-side hydration mechanism reads them and adds them to the Vuex store. The t function then looks up the translations and displays them where needed. These translations are reactive and accept data parameters to format translations.
We use Vue SFC to render user flows in an SPA-like fashion, although the site is not yet an SPA.
The problem
In order for this to work the translations required for a page have to be listed in the back-end controller methods in a dictionary.
This has become un-maintainable and much more data is shipped to the front-end than what is necessary. Additionally, the back-end system has no definitive end-point when a page is built before being shipped to the browser that we can hook into in order to add the translations to the HTML and content often end up being duplicated.
The back-end system was built using DotNet MVC 4, so we have no SSR capabilities at this point.
The solution (hopefully)
In order to better maintain our code I would like to utilise the 't' function from the plugin to load translations via an AJAX call before the vue engine has rendered the template, i.e. via the beforeCreate or created hook. The problem is that the Vue instance will have to know about translations required in child component templates before the AJAX call can be fired, and I have no idea how to accomplish this.
On a side note, delaying rendering like this goes against all my instincts but it doesn't look like we have a choice at this point.
I am planning to cache the translations client side with a content hash in case they get updated, so the ajax calls will hopefully not be required very often, only on first load.
The site is gradually being converted into an SPA, at which point I will be able to split off the FE and utilise SSR via node. Up until that point though this is the best idea I could come up with.
Any help will be greatly appreciated.

I have been thinking about this my self as at the moment I just send an entire cached json to the client on App Init with a loading screen, is not bad at the moment since there is not a lot to translate but was considering the following approach otherwise:
Have an array in the translation vuex module store a list of keys that need to translate (array).
Have t() push the keys to translate if not already in translated store and return either empty string or a placeholder until the translation is re-actively available.
On mounted dispatch a fetch method on the store to perform the ajax call and set the translation state and clear out the translate list when complete.
Vue should by default it's behavior re-render upon the VUEX state being changed and cause t() in the template body to be recalled and return matching values on nextTick instead of placeholder value previously returned.

Related

Why use Vuex in SSR?

My question is, what's the point of setting up Vuex for the server when the state will be overwritten when the client side hydration takes place?
I have some data (Helm env variables) that I want to store in the vuex store for later use.
These variables is only available to me on the server, so I started trying to add them to the store in my createApp script when running on the server.
The store state however is reset when the client side hydration kicks in, so no env variables left.
Google told me I should use like window.INITIAL_DATA to set the state again on the client:
store.replaceState(window.INITIAL_DATA)
But if have to use the window object to pass store data to the client, what's the point of using Vuex on the server at all?
Isn't it better to skip Vuex overhead on the server and just use Vuex on the client and populate it with INITIAL_DATA?
I'm probably missing something..
https://ssr.vuejs.org/guide/data.html#data-store
During SSR, we are essentially rendering a "snapshot" of our app. The asynchronous data from our components needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.
To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store while rendering. In addition, we will serialize and inline the state in the HTML after the app has finished rendering. The client-side store can directly pick up the inlined state before we mount the app.
Also to mention:
The data you access while SSR in any Component needs to come from somewhere if you want to share information across Components, this is what Vuex is there for.

Multiple Vue apps, multiple entry files, same Vuex/Vue3CompostitionApi store [lost reactivity]

I am trying to iteratively replace .cshtml razor views with what I wanted to call Vue "mini-apps". Which should be somewhere in between a micro-frontend and a classic SPA. The aim is to share some of the code base, mainly dependencies. Compile a common chunk-vendors.js and have the "mini-apps" as separate javascript entry files to place on appropriate views. As performance demand would grow, I would progress into splitting chunk-vendors.js and optimize via lazy-loading.
The problem I am hitting here is trying to make two root Vue instances talk to each other through a shared state. Right now only the app that is imported/mounted first stays reactive. I thought that my problem was in the Vue 2 reactivity system/how Vuex binds itself to a concrete Vue instance here. When I implemented a primitive store, the situation ended up being exactly the same.
What confuses me about this is that if I were to instantiate two applications in a single main.js entry file, the store sharing would just work. Which suggest that Vue is either creating some kind of hidden root instance or that my Vuex code analysis deduction of it binding to a concrete instance was incorrect.
I would highly appreciate it if someone could tell me why this can't work, optionally suggest a workaround?
I have created a reproduction both in Vue 2 with Vuex and in Vue 3 with composition API/primitiveStoreImplementation here.
Vue-cli is building the app in an MPA mode with pages specified in vue.config.json, then imported in the root index.html file. The store is initialised once and saved for later check/loading on the window object. In the context of asp/razor I would have webpack set up to remove the redundant files, only leaving javascript bundles. Also, the dev proxy would proxy everything except the path to the script bundles. All of this is removed for the sake of the demonstration.
(once I find a solution I hope to replace the source link with specific code snippets)
Options considered:
I am trying to avoid it, but I might have to always run a "coordinator" root instance that will check the presence of certain elements on a page and load/unload the "mini-apps" as components using something like portal-vue when needed. That coordinator would also contain a state with modules, some of which would be marked as "shared" thus operations from multiple "mini-apps" would be allowed (ownership flag check).
I have considered sessionStorage/localStorage, the problem is that the 'storage' events are only triggered across tabs and not within one document first |Note. I would have to trigger a custom event or play around with iframes. Feels too hacky, but that might be an axiom here. It would also duplicate the same state across many store instances.
These are some relevant articles I have found on this topic:
Probably closest to what I am trying to achieve:
Using Vuex with multiple Vue instances
Same but different:
Build Vue microfrontend app (with routing and vuex store)
The use case for multiple entries are sub-apps that don't coexist on the same page, although they can. They could be web components or regular app bundles. They can even interact with each other but they need something else for this - global event bus or a mediator app that passes data between them.
The problem is that there are more than one Vue library copies and/or more than one Vuex store instance. In order to avoid this, they would need to be precisely loaded only once on the page and reused between apps, i.e. vue and vuex are loaded as CDN libs, possibly used as Webpack externals to use window.Vue and window.Vuex transparently for respective import. Not only Vuex but store needs to be a singleton on the page (basically a said mediator). This is acceptable solution but primarily suitable for existing applications that have design restrictions and need a workaround.
I am trying to avoid it, but I might have to always run a "coordinator" root instance that will check the presence of certain elements on a page and load/unload the "mini-apps" as components using something like portal-vue when needed.
This is the common way to do this. Vue 3 has teleports that has give less control than portal-vue. It has no downsides for application design if done properly. The same thing is achieved similarly in other frameworks (Angular, React) as well, where portals appeared earlier.
I have considered sessionStorage/localStorage, the problem is that the 'storage' events are only triggered across tabs and not within one document
This is solved by using window postMessage and message event in the same tab. In case this shouldn't be limited to a single window, there are third party libs that use both for cross-tab synchronzation, a native alternative is BroadcastChannel that has less browser support than LS but doesn't have its limitations regarding tabs.

Vue page cannot open after refreshing the page

I added the routes dynamically to the router and I can visit all pages with router-view. However, when I try to refresh the page I cannot visit the page again although the URL is the same. It is http://localhost:8081/me.
this.$router.addRoute("Main", {
path: '/me',
name: 'Me',
component: () => import(`#/components/Me.vue`)
});
As I said, I can normally visit the page "Me", but when I refresh it, I cannot see its content anymore with the warning:
[Vue Router warn]: No match found for location with path "/me"
I tried to create router with createWebHistory("/") after reading the cause of the error but nothing seems to change. I will appreciate any help.
There are two reasons why this would happen.
First serving SPA application from the server.
Make sure that your back-end is set to serve index.html file for all routes since back-end server is unaware of the routes set by client-side router. Something like express-history-api-fallback-middleware can help is using Node.js/Express.js.
Second problem is that of using addRoute.
As you described, the problem could be that Vue router is taking routing decision before your code in components/common/LeftMenu.vue is getting executed which is responsible for calling addRoute(). Ensure that this code is called before routing decision is being made. Best way would be to move this logic in top-level application component. And, if you can move that to top-level components, that means you can try to declare all routes while defining the router.
Why that should be done?
Using addRoute is not necessarily an anti-pattern but having to rely on addRoute is often code smell. You would really need it in extremely rare scenarios. Routing is a high-level architectural concern for your application and thus better to be declared upfront somewhere at top-level module even before application is getting initialized. Low level components should not attempt to manipulate routing data structure (violation of DIP principles).
One scenario where you might be tempted to use addRoute is taking decision after some data manipulation by the component with addition of some API call. That seems legitimate need but then to address that there are better ways. Considering using route guards (guards support async resolution too!) and prevent user from entering the view till the guard is resolved successfully.

How to not rerender a component when revisiting a page in Nuxt.js?

When I visit another page and come back, I want to express the Google Maps coordinates and data that I had.
There's a lot of data that needs to be handled to use the Store, so it's hard to use.
I wonder if there is a way to recycle pages without erasing them from DOM.
If you wish to preserve the page's content as is while navigating, you may use keep-alive which will cache the route's content. See docs here.
However, my personal experience is that caching Vue or Nuxt pages with keep-alive sometimes leads to unexpected bugs in my applications since oftentimes I write code with the expectation that all the values I defined in data() are going to have the default value. But that's not the case when caching the components.
As you've said, this requirement often arises when some expensive data have been fetched. I prefer to either cache this fetch result (mostly in local storage) or in Vuex Store. One can then safely destroy the component when navigating away and reuse the cached data when navigating back, but the component will be otherwise initialized with the default data().
You can use keep-alive attribute:
https://nuxtjs.org/docs/2.x/features/nuxt-components#keep-alive
Then your mounted lifecycle will called only once.
But, there is no prevention to store huge amount of data in the vuex store.

Assign/add mixin or sub-component at runtime?

Can I dynamically add a mixin? I think I read that runtime insertion of mixins is not supported and will never be. Is the below runtime insertion possible?
My usecase is; all our pages are stored in a database, each page standard properties like; title, content and template. We have components for each template. Each template component displays the title and content differently. So I need to build the routes and say this page uses this (template) component. Maybe I can use sub-components to achieve this? Can I dynamically add sub-components at runtime?
The easiest solution is to do the following:
Router:
// myPages retrieved by REST call
const routes = _.map(myPages, page => {
return {
path: `/${page.url}`,
name: page.name,
component: DefaultPage // make all pages use DefaultPage component
}
});
DefaultPage.vue
<template>
</template>
<script>
import mixins from './mixins';
export default {
mixins: [mixins.Base]
beforeMount() {
// I dont think this is possible?
let templateMixin = mixins[ this.page.template ]
this.mixins.push( templateMixin );
}
}
</script>
Maybe its possible to assign a sub-component at runtime?
<template>
// Somehow call the sub-component (template)?
<template></template>
</template>
<script>
import templates from './templates';
export default {
components: {},
beforeMount() {
// Is this possible?
let templateCmp = templates[ this.page.template ]
this.components = {
templateCmp
}
}
}
</script>
Unfortunately there is a lot of misinformation on the web stating that "because of userland perils, it's not safe or secure to load dynamic or "runtime" components", and that doing so is "a security risk".
This stems from the reasoning that Vue uses the eval statement when compiling components. However, so does React and Angular. There is in fact no way to compile components without this. while eval is a sharp knife, so is any JavaScript. Saying that a sharp knife is insecure is false as long as you keep that sharp knife itself secure.
The notion that runtime components is insecure is utterly and completely false. There are tons of officially supported ways to do this if you control the source. In fact, there is even an officially Vue supported "userland" method to load dynamic/async components even if you don't control the source(!!)
Async components
Probably the easiest way to load a page from a database (which itself may have it's own sub-components, mixins and dependencies), is with async components.
This is an official part of Vue and I've used it in dozens of production apps. It works exactly like expected; nothing is invoked by your application until all the conditions are met, and when the load conditions are met, you are free to obtain the component however you see fit.
Note: You must control the source of these components, or XSS injection and other hacking is possible.
If you're using webpack, it's easy to get all the components dependencies into a single file. In the above URL are specific how-to articles including a video tutorial of how to produce a single js file for your pages dependencies that aren't part of your main application.
One caveat for loading multiple sub components this way is you may overlap/repeat loading (i.e. page A may load 5 sub components that no other static page loads, and page B may load 5 sub components, 3 of which are shared with page A, and 2 of which are specific to page B). Caveats like these can mess up your optimization techniques if you don't think them through. This can be unavoidable and fine, and still much faster than loading the entire app at once though.
Async components in userland
If you only want to load custom templates from a database (i.e. if you don't want to allow users to load their own custom components, mixins, filters, directives, etc), with each template, then you are in luck; Vue even has official support for async templates that are locked-down to only allowing template changes. This is enough to offer your component builders scaffolding for creating an app, but prevents them from executing arbitrary JavaScript code (this method won't let them setup a data section, or hook into the component lifecycle for example).
v-runtime-template is officially recognized by the Vue.js team as the official method for creating userland-safe Vue templates.
I've used v-runtime-template in platforms used by some of the biggest names in the industry across tens of millions of users without a single security breach, because this method only exposes the components you say are OK.
Further template lockdown using JSON schemas
If you need only form generation, or you can simplify your components further, and you only need to reason about data in simple ways like queries (i.e. if you're building a survey generator, or an analytics or other widget dashboard), you can build components out of JSON Schemas using vue-form-json-schema. This method takes 2 schemas: one for your data, and one for your form. The parent component you load specifies all the components that are accessible to the schema, so you must whitelist components that userland has access to, further, the forms cannot run arbitrary JavaScript, they can only call functions that you make available in the parent component, which are your JavaScript whitelist.
Userland-Safe Queries on arbitrary data
You can let users query specific JSON objects for use in completely-safe userland queries that can be provided by the public using JSONata. Developed by IBM, JSONata is a way to safely query and, with the exposure of a few functions, allows your users to even manipulate data in verified-safe ways.
Although JSONata is logically proven to be safe in unserland, it is also Turing-complete without functions, meaning your users can manipulate the Schema provided data by outputting new data that can technically do anything; i.e. your users can create Doom 3 using JSONata queries. People have made games like Pong and other interesting things out of JSONata.
JSONata's power cannot be overstated. It powers the magic behind nearly all no-code/low-code platforms like the open source Node-RED, and is behind many other proprietary no-code/low-code platforms that are closed source, including Google, Microsoft, Amazon and IBM platforms.
They use JSONata to translate data schemas between platforms, and whenever business logic is needed on data manipulation, and the manipulation must be left in user-land (i.e. an app that needs to manipulate data, but you want to run that app on your platform and not have to worry about QA or people being able to hack or write a nefarious app that breaks into your platform).