How can I load an nested component dynamically in Vuejs without hardcoding the url - vue.js

I followed Markus Oberlehner for loading Vue components via http. We have a Vue component precompiled as a .js file hosted on a separate server. When the user navigates to this loader component below, the call to externalComponent() successfully fetches the .js file and renders the component on this page. That is great. This only works if we hardcode the url in the loader component.
We are building a plugin architecture into our site. We have written some single page Vue component files. Each of these files is a plugin. We precomiled these .vue files into .js files according to Markus Oberlehner's helpful tutorial here: https://github.com/maoberlehner/distributed-vue-applications-loading-components-via-http.
We also have a Vue component in our main site - let's call it the loader component - that fetches a .js file and renders it into a component using the externalComponent() method - demonstrated in Markus's tutorial. This works, but since the MyComponent is a constant defined outside of the loader component's data object, we cannot dynamically inject the plugin_id of from the vue router into the .js file's url.
If you're curious why our urls don't end in .js it is because we are passing a url to an endpoint in our server instead. This endpoint fetches the .js file and returns it to our client.
<template>
<div>
<MyComponent />
</div>
</template>
<script>
import util from "~/js/util.js";
let MyComponent = () =>
/* If we hadcode the url, the page renders no problemo.
*
* util.externalComponent("http://localhost:8081/api/plugins/167/code");
*/
/* However, we'd like to fetch the plugin_id from the Vue router and inject that into the argument
* as I've tried to achieve in the line of code below.
*
* The following code does not work because Vue apparently loads the MyComponent element in the DOM
* before executing the created() hook. We get the error "plugin_id is not defined."
*/
util.externalComponent(
"http://localhost:8081/api/plugins/" + plugin_id + "/code"
);
export default {
name: "plugin",
components: {
MyComponent
},
data() {
return {
plugin_id: null
};
},
created() {
/* This line does indeed populate the plugin_id data variable, although this happens after the
* page attempts to load MyComponent
*/
this.plugin_id = this.$route.params.plugin_id;
}
};
</script>
So, how can we modify this code to dynamically insert the plugin_id into the url?
This is a nuxt project by the way.
Update
Here is an approach that works the first time I load the page, but consecutive loads are still a problem. Specifically, the first component just loads again regardless of whatever the new plugin id may be.
But this looks like the right direction...
<template>
<div>
<component v-bind:is="component" v-if="loadedUrl"></component>
{{ plugin_id }}
</div>
</template>
<script>
import util from "~/js/util.js";
export default {
name: "plugin",
props: [],
data() {
return {
loadedUrl: false,
component: null
};
},
beforeRouteEnter(to, from, next) {
next(vm => {
vm.loadedUrl = false;
vm.component = () =>
util.externalComponent(
"http://localhost:8081/api/plugins/" + to.params.plugin_id + "/code"
);
vm.loadedUrl = true;
next();
});
},
beforeDestroy() {
//does not seem to help.
console.log("in beforeDestroy");
this.component = null;
}
};
</script>

Related

How to create dynamic components in vueJS

I am new to vueJS and am trying to load components dynamically. I searched on the web and experimented with many suggestions but am still not able to get it to work.
Scenario: I want to have a 'shell' component that acts as a container for swapping in and out other components based on user's selection. The file names of these components will be served up from a database
Here's the shell component:
<template>
<keep-alive>
<component :is='compName'></component>
</keep-alive>
</template>
<script>
props: ['vueFile'],
export default ({
data() {
compName: ()=> import('DefaultPage.vue')
},
watch: {
compName() {
return ()=> import(this.vueFile);
}
}
})
</script>
This does not work.
If I hard code the component file name, it works correctly... e.g.
return ()=> import('MyComponent.vue');
The moment I change the import statement to use a variable, it gives an error even though the variable contains the same string I hard code.
What am I doing wrong?
compName() {
const MyComponent = () => import("~/components/MyComponent.js");
}
You can see this post
https://vuedose.tips/dynamic-imports-in-vue-js-for-better-performance
You can put the components you want to add dynamically in a directory, for example: ./component, and try this
compName () {
return ()=> import(`./component/${this.vueFile}`);
}
The import() must contain at least some information about where the module is located.
https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

Same VueX store module registered from components on two pages

I have encountered a weird case when using VueX and Vue-Router and I am not too sure how to cleanly solve it.
I have a component (let's call it "ComponentWithStore") that registers a named store module a bit like this : (the actual content of the store don't matter. obviously in this toy example using VueX is overkill, but this is a very simplified version of a much more complexe app where using VueX makes sense)
// ComponentWithStore.vue
<script>
import module from './componentStore.js';
export default {
name: 'ComponentWithStore',
beforeCreate() {
this.$store.registerModule(module.name, module);
},
beforeDestroy() {
this.$store.unregisterModule(module.name);
}
}
</script>
Then I place this component in a view (or page) which is then associated to a route (let's call this page "Home").
// Home.vue
<template>
<div class="home">
Home
<ComponentWithStore/>
</div>
</template>
<script>
import ComponentWithStore from '#/components/ComponentWithStore.vue';
export default {
name: "Home",
components: { ComponentWithStore }
};
</script>
So far so good, when I visit the Home route, the store module is registered, and when I leave the Home route the store module is cleaned up.
Let's say I then create a new view (page), let's call it "About", and this new About page is basically identical to Home.vue, in that it also uses ComponentWithStore.
// About.vue
<template>
<div class="about">
About
<ComponentWithStore/>
</div>
</template>
<script>
import ComponentWithStore from '#/components/ComponentWithStore.vue';
export default {
name: "About",
components: { ComponentWithStore }
};
</script>
Now I encounter the following error when navigating from Home to About :
vuex.esm.js?2f62:709 [vuex] duplicate namespace myComponentStore/ for the namespaced module myComponentStore
What happens is that the store module for "About" is registered before the store module for "Home" is unregistered, hence the duplicate namespace error.
So I understand well what the issue is, however I am unsure what would be the cleanest solution to solve this situation. All ideas are welcome
A full sample may be found here : https://github.com/mmgagnon/vue-module-router-clash
To use, simply run it and switch between the Home and About pages.
As you have mentioned, the issue is due to the ordering of the hooks. You just need to use the correct hooks to ensure that the old component unregisters the module first before the new component registers it again.
At a high level, here is the order of hooks in your situation when navigating from Home to About:
About beforeCreate
About created
Home beforeDestroy
Home destroyed
About mounted
So you can register the module in the mounted hook and unregister it in either beforeDestroy or destroyed.
I haven't tested this though. It might not work if your component requires access to the store after it is created and before it is mounted.
A better approach is to create an abstraction to register and unregister modules that allows for overlaps.
Untested, but something like this might work:
function RegistrationPlugin(store) {
const modules = new Map()
store.registerModuleSafely = function (name, module) {
const count = modules.get(name) || 0
if (count === 0) {
store.registerModule(name, module)
}
modules.set(name, count + 1)
}
store.unregisterModuleSafely = function (name) {
const count = modules.get(name) || 0
if (count === 1) {
store.unregisterModule(name)
modules.delete(name)
} else if (count > 1) {
modules.set(name, count - 1)
}
}
}
Specify the plugin when you create your store:
const store = new Vuex.Store({
plugins: [RegistrationPlugin]
})
Now register and unregister your modules like this:
beforeCreate() {
this.$store.registerModuleSafely(module.name, module)
},
destroyed() {
this.$store.unregisterModuleSafely(module.name)
}

Vue/Nuxt: How to define a global method accessible to all components?

I just want to be able to call
{{ globalThing(0) }}
in templates, without needing to define globalThing in each .vue file.
I've tried all manner of plugin configurations (or mixins? not sure if Nuxt uses that terminology.), all to no avail. It seems no matter what I do, globalThing and this.globalThing remain undefined.
In some cases, I can even debug in Chrome and see this this.globalThing is indeed defined... but the code crashes anyway, which I find very hard to explain.
Here is one of my many attempts, this time using a plugin:
nuxt.config.js:
plugins: [
{
src: '~/plugins/global.js',
mode: 'client'
},
],
global.js:
import Vue from 'vue';
Vue.prototype.globalFunction = arg => {
console.log('arg', arg);
return arg;
};
and in the template in the .vue file:
<div>gloabal test {{globalFunction('toto')}}</div>
and... the result:
TypeError
_vm.globalFunction is not a function
Here's a different idea, using Vuex store.
store/index.js:
export const actions = {
globalThing(p) {
return p + ' test';
}
};
.vue file template:
test result: {{test('fafa')}}
.vue file script:
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions({
test: 'globalThing'
}),
}
};
aaaaaaaaand the result is.........
test result: [object Promise]
OK, so at least the method exists this time. I would much prefer not to be forced to do this "import mapActions" dance etc. in each component... but if that's really the only way, whatever.
However, all I get is a Promise, since this call is async. When it completes, the promise does indeed contain the returned value, but that is of no use here, since I need it to be returned from the method.
EDIT
On the client, "this" is undefined, except that..... it isn't! That is to say,
console.log('this', this);
says "undefined", but Chrome's debugger claims that, right after this console log, "this" is exactly what it is supposed to be (the component instance), and so is this.$store!
I'm adding a screenshot here as proof, since I don't even believe my own eyes.
https://nuxtjs.org/guide/plugins/
Nuxt explain this in Inject in $root & context section.
you must inject your global methods to Vue instance and context.
for example we have a hello.js file.
in plugins/hello.js:
export default (context, inject) => {
const hello = (msg) => console.log(`Hello ${msg}!`)
// Inject $hello(msg) in Vue, context and store.
inject('hello', hello)
// For Nuxt <= 2.12, also add 👇
context.$hello = hello
}
and then add this file in nuxt.config.js:
export default {
plugins: ['~/plugins/hello.js']
}
Use Nuxt's inject to get the method available everywhere
export default ({ app }, inject) => {
inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
Make sure you access that function as $myInjectedFunction (note $)
Make sure you added it in nuxt.config.js plugins section
If all else fails, wrap the function in an object and inject object so you'd have something like $myWrapper.myFunction() in your templates - we use objects injected from plugins all over the place and it works (e.g. in v-if in template, so pretty sure it would work from {{ }} too).
for example, our analytics.js plugin looks more less:
import Vue from 'vue';
const analytics = {
setAnalyticsUsersData(store) {...}
...
}
//this is to help Webstorm with autocomplete
Vue.prototype.$analytics = analytics;
export default ({app}, inject) => {
inject('analytics', analytics);
}
Which is then called as $analytics.setAnalyticsUsersData(...)
P.S. Just noticed something. You have your plugin in client mode. If you're running in universal, you have to make sure that this plugin (and the function) is not used anywhere during SSR. If it's in template, it's likely it actually is used during SSR and thus is undefined. Change your plugin to run in both modes as well.
This would be the approach with Vuex and Nuxt:
// store/index.js
export const state = () => ({
globalThing: ''
})
export const mutations = {
setGlobalThing (state, value) {
state.globalThing = value
}
}
// .vue file script
export default {
created() {
this.$store.commit('setGlobalThing', 'hello')
},
};
// .vue file template
{{ this.$store.state.globalThing }}

How do I refer to custom Javascript file in my Vuepress project so the JS functions are globally available?

I am working on a Vuepress project which was setup by a former colleague. I am trying to refer my custom Javascript file in a root component so that it is globally available. I don't want to refer to it in every component, because that would be redundant and it does not work as expected.
I read enhanceApp.js is the way to go so I tried attaching the JS file to Vue Object but it does not work. Any help is appreciated!
This is enhanceApp.js
import HelpersPlugin from '../../src/js/helpers';
export default ({
Vue,
options,
router, // the router instance for the app
siteData // site metadata
}) => {
Vue.use(HelpersPlugin);
}
this is src/js/helpers folder which contains, accordion.js (My custom JS file) and index.js
index.js:
import AccordionHelper from './accordion';
export default {
install: (Vue, options) => {
Vue.prototype.$helpers = {
accordion: AccordionHelper
}
}
}
accordion.js: (has plain JS with DOM manipulation functions)
export default () => {
console.log("Hello");
//DOM manipulation JS
}
This is the folder structure:
docs
-> .vuepress
- components
* Accordion.vue
* Buttons.vue
- theme
* Layout.vue
* SearchBox.vue
- config.js
- enhanceApp.js
-> accordion
- README.md
-> buttons
- README.md
src
-> js
- helpers
* accordion.js
* index.js
I am looking to use accordion.js in both Accordion.vue and Layout.vue without having to refer it in both components.
I believe this is the recommended way of sharing common JS functions.
Found this by ejecting the default theme from Vuepress.
.vue File:
<template>
<div v-if="canHelp()">Help is on the way</div>
</template>
<script>
import { canHelp } from './helpers'
export default {
methods: {
canHelp
}
}
</script>
helpers.js
export function canHelp () {
return true
}

vue js trigger other component method

my files looks like this
./components/UserCreate.vue
./components/UserList.vue
./main.js
my vue instance in main.js
new Vue({
el: '#user-operations',
components: {
CreateUser,
UserList
}
});
index.html
<div id="user-operations">
<create-user></create-user>
<user-list></user-list>
</div
I want to trigger userList() method in UserList.vue when createUser() method in CreateUser.vue is triggered. Or how can i pass last_user property to UserList component from CreateUser.vue for append.
here is my create-user component [working]
https://jsfiddle.net/epp9y6vs/
here is my user-list component [working]
https://jsfiddle.net/ore3unws/
so i want the last user to be listed when createUser() is triggered
I recommend to create a service with all the methods operating user entities. It will separate your Components from the implementaton of the logic which is good because:
The Components doesn't have to know which calls they have to do to servers to retrieve data - it's better to use abstraction level
The Component will be lighter and easier for reuse
You will be able to use this logic (from the service) in several Components - exactly your problem
You have several ways to implement services:
Stateless service: then you should use mixins
Statefull service: use Vuex
Export service and import from a vue code
any javascript global object
I prefer (4). Here is an example how to do it:
In file /services/UsersService that will describe your service put all the relevant methods and expose them with export:
import axios from 'axios'
export default {
get() {
return axios.get('/api/posts)
}
}
Then in any Component that needs this methods import this service:
import UsersService from '../services/UsersService'
export default {
data() {
return {
items: []
}
},
created() {
this.fetchUsers()
},
methods: {
fetchUsers() {
return UsersService.get()
.then(response => {
this.items = response.data
})
}
}
}
Find even more about it in this question:
What's the equivalent of Angular Service in VueJS?
This solution is much better than using this.$parent.$refs.userList which suppose that this components will always stay "brothers" (will have the same parent).
You can trigger userList in CreateUser.vue by this code:
this.$parent.$refs.userList.userList()
and change your index.html:
<div id="user-operations">
<create-user></create-user>
<user-list :ref="userList"></user-list>
</div>
You can create last_user property in main.js then pass it to 2 components:
.
<div id="user-operations">
<create-user:lastUser="last_user"></create-user>
<user-list :lastUser="last_user"></user-list>
</div>